/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/6/15
 */
package org.ts.ddcs.CheckController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.CheckController.Service.CheckService;
import org.ts.ddcs.CheckController.Service.Entity.RtuCheckInfo;
import org.ts.ddcs.Log.LogHelper;
import org.ts.ddcs.UserController.entity.UserEntity;
import org.ts.ddcs.UserController.service.UserService;
import org.ts.ddcs.WxController.service.WxService;
import org.ts.ddcs.utils.GBConstants;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/***
 * Date:2022/6/15
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("/Dev/Wx/check")
public class CheckController {
    @Autowired
    private UserService userService;

    @Autowired
    private CheckService checkService;

    @Value("${run-config.server.projectImplementPhotoPath}")
    private String projectImplementPhotoPath;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private WxService wxService;


    @GetMapping(value = {"/list/{openId}"})
    @ResponseBody
    public JSONObject checkList(@PathVariable(name = "openId") String openId, HttpServletRequest request) {

        try {
            UserEntity userEntity = this.userService.getUserInfoByOpenId(openId);
            if (null == userEntity) {
                JSONObject json = new JSONObject();
                json.put("code", "1");
                json.put("msg", "微信公众开放ID异常，请重试！");
                return json;
            }
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            JSONObject json = new JSONObject();
            String orgId = userEntity.getOrgId();
            if (GBConstants.ORG_ID_DH.equals(orgId)) {
                orgId = null;
            }
            List<RtuCheckInfo> list = this.checkService.list(orgId);
            for (RtuCheckInfo checkInfo : list) {
                if (null == checkInfo.getCheckTitle()) {
                    if (null != checkInfo.getRtuName()) {
                        checkInfo.setCheckTitle(checkInfo.getRtuName());
                    } else {
                        if (null != checkInfo.getRtuCode()) {
                            checkInfo.setCheckTitle(checkInfo.getRtuCode());
                        } else {
                            checkInfo.setCheckTitle("--");
                        }
                    }
                }
                if (null == checkInfo.getWarningDesc()){
                    checkInfo.setWarningDesc("--");
                }
                String time = timeFormat.format(checkInfo.getUpdateTime());
                checkInfo.setUpdateTimeText(time);
                time = timeFormat.format(checkInfo.getCreateTime());
                checkInfo.setCreateTimeText(time);
                if (checkInfo.getProcessStatusId().equals(GBConstants.DICT_CHECK_PROCESS_STATUS_COMPLETE)){
                    checkInfo.setCloseStatus("1");
                }else{
                    checkInfo.setCloseStatus("0");
                }
            }
            json.put("data", list);
            json.put("code", "0");
            return json;
        } catch (Exception e) {
            JSONObject json = new JSONObject();
            json.put("code", "1");
            json.put("msg", e.getMessage());
            return json;
        }
    }

    @GetMapping(value = {"/{checkId}"})
    @ResponseBody
    public JSONObject getCheckInfo(@PathVariable(name = "checkId") String checkId) {
        JSONObject json = new JSONObject();
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            RtuCheckInfo rtuCheckInfo = this.checkService.checkInfo(checkId);
            if (null == rtuCheckInfo.getUpdateUser()) {
                rtuCheckInfo.setUpdateUser("");
            }
            if (null == rtuCheckInfo.getCreateUser()) {
                rtuCheckInfo.setCreateUser("");
            }
            String time = timeFormat.format(rtuCheckInfo.getUpdateTime());
            rtuCheckInfo.setUpdateTimeText(time);
            time = timeFormat.format(rtuCheckInfo.getCreateTime());
            rtuCheckInfo.setCreateTimeText(time);
            if (rtuCheckInfo.getProcessStatusId().equals(GBConstants.DICT_CHECK_PROCESS_STATUS_COMPLETE)){
                rtuCheckInfo.setCloseStatus("1");
            }else{
                rtuCheckInfo.setCloseStatus("0");
            }
            json.put("data", rtuCheckInfo);
            json.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            json.put("code", "1");
            json.put("msg", e.getMessage());
        }
        return json;
    }

    @PostMapping(value = "/process/{checkId}")
    @ResponseBody
    public JSONObject processReport(@PathVariable(name = "checkId") String checkId, @RequestBody final JSONObject body) {
        JSONObject json = new JSONObject();
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String openid = body.getString("openid");
            UserEntity userEntity = userService.getUserInfoByOpenId(openid);
            RtuCheckInfo rtuCheckInfo = new RtuCheckInfo();
            rtuCheckInfo.setId(checkId);
            rtuCheckInfo.setServicePersonId(userEntity.getId());
            rtuCheckInfo.setProcessStatusId(GBConstants.DICT_CHECK_PROCESS_STATUS_SUGGESTION);
            rtuCheckInfo.setProcessSuggest(body.getString("processSuggest"));
            rtuCheckInfo.setCreateUser(userEntity.getId());

            if (body.containsKey("photos")) {
                JSONArray photos = body.getJSONArray("photos");
                ArrayList<String> photoList = new ArrayList<>(photos.size());
                for (int i = 0; i < photos.size(); i++) {
                    JSONObject p = photos.getJSONObject(i);
                    photoList.add(p.getString("id"));
                }
                rtuCheckInfo.setPhotos(photoList);
            }
            this.checkService.saveProcess(checkId, rtuCheckInfo);
            json.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            json.put("errMsg", "fail");
            json.put("code", "1");
        }
        return json;
    }


    @GetMapping(value = {"/process/list/{checkId}"})
    @ResponseBody
    public JSONObject checkProcessList(@PathVariable(name = "checkId") String checkId) {
        JSONObject json = new JSONObject();
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            List<RtuCheckInfo> list = this.checkService.processList(checkId);
            for (RtuCheckInfo checkInfo : list) {
                String time = timeFormat.format(checkInfo.getUpdateTime());
                checkInfo.setUpdateTimeText(time);
                time = timeFormat.format(checkInfo.getCreateTime());
                checkInfo.setCreateTimeText(time);
            }
            json.put("data", list);
            json.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            json.put("code", "1");
            json.put("msg", e.getMessage());
        }
        return json;
    }

    @GetMapping(value = {"/process/{processId}"})
    @ResponseBody
    public JSONObject getProcessInfo(@PathVariable(name = "processId") String processId) {
        JSONObject json = new JSONObject();
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            RtuCheckInfo rtuCheckInfo = this.checkService.processInfo(processId);
            if (null == rtuCheckInfo.getUpdateUser()) {
                rtuCheckInfo.setUpdateUser("");
            }
            if (null == rtuCheckInfo.getCreateUser()) {
                rtuCheckInfo.setCreateUser("");
            }
            String time = timeFormat.format(rtuCheckInfo.getUpdateTime());
            rtuCheckInfo.setUpdateTimeText(time);
            time = timeFormat.format(rtuCheckInfo.getCreateTime());
            rtuCheckInfo.setCreateTimeText(time);
            List<String> photos = this.checkService.processPhotos(processId);
            if (null != photos) {
                rtuCheckInfo.setPhotos(photos);
            } else {
                rtuCheckInfo.setPhotos(new LinkedList<>());
            }
            json.put("data", rtuCheckInfo);
            json.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            json.put("code", "1");
            json.put("msg", e.getMessage());
        }
        return json;
    }

    @PostMapping(value = "/upload/image")
    @ResponseBody
    public JSONObject checkUploadImage( @RequestParam("image") MultipartFile image) {
        JSONObject json = new JSONObject();
        if (image != null) {
            try {
                String originalFilename = image.getOriginalFilename();
                long fileSize = image.getSize();
                InputStream input = image.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = input.read(buffer)) > -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                byteArrayOutputStream.flush();
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                String[] ofs = originalFilename.split("[.]");
                String toPath = projectImplementPhotoPath;
                File dir = new File(toPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                String fileName = uuid + "." + ofs[ofs.length - 1];
                File file = new File(toPath + File.separator + fileName);
                FileOutputStream outputStream = new FileOutputStream(file);
                while (true) {
                    byte[] buff = new byte[1024];
                    int r = byteArrayInputStream.read(buff, 0, 1024);
                    if (r > 0) {
                        outputStream.write(buff, 0, r);
                    }
                    if (r <= 0) {
                        break;
                    }
                }
                outputStream.close();
                String ext = ofs[ofs.length - 1];
                String type = "";
                if (ext.equals("jpg") || ext.equals("jpeg")) {
                    type = "image/jpeg";
                } else if (ext.equals("png")) {
                    type = "image/png";
                } else if (ext.equals("bmp")) {
                    type = "image/bmp";
                }
                byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                FastImageFile fastImageFile = new FastImageFile(byteArrayInputStream, fileSize, ext, null);
                StorePath storePath = fastFileStorageClient.uploadImage(fastImageFile);
                String photoUrlPath = storePath.getFullPath();

                this.wxService.SavePhoto(uuid, null, originalFilename, image.getSize(), ext, type, photoUrlPath, 2);
                json.put("code", "0");
                json.put("photoUrl", photoUrlPath);
                json.put("fileId", uuid);
            } catch (IOException e) {
                LogHelper.error(e);
                json.put("errMsg", "fail");
                json.put("code", "1");
            }
        } else {
            json.put("errMsg", "canot found image");
            json.put("code", "1");
        }
        return json;
    }
}
