package digital.laboratory.platform.entrustment.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import digital.laboratory.platform.common.core.constant.CommonConstants;
import digital.laboratory.platform.common.core.constant.OSSDirectoryConstants;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.log.annotation.SysLog;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.common.oss.service.OssFile;
import digital.laboratory.platform.entrustment.convert.CaseEventConvert;
import digital.laboratory.platform.entrustment.dto.UpdateCaseAndEntrustTypeDTO;
import digital.laboratory.platform.entrustment.entity.*;
import digital.laboratory.platform.entrustment.service.*;
import digital.laboratory.platform.entrustment.vo.CaseEventVO;
import digital.laboratory.platform.othersys.vo.EntrustDataVo;
import digital.laboratory.platform.sys.entity.SysOrg;
import digital.laboratory.platform.sys.feign.RemoteOrgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 案件事件
 *
 * @author Zhang Xiaolong created at  2022-03-22
 * @describe 案件事件 前端控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/papp/entrustment/case")
@Api(tags = "001-案件管理")
public class CaseEventController {

    private final CaseEventService caseEventService;

    private final CaseEvidenceService caseEvidenceService;

    private final EntrustmentService entrustmentService;

    private final EntrustmentIdentificationMaterialService entrustmentIdentificationMaterialService;

    private final RemoteOrgService remoteOrgService;

    private final OssFile ossFile;

    private final SuspectService suspectService;


    /**
     * 通过id查询案件事件
     *
     * @param id      id
     * @param forEdit 如果为true, 表示为编辑而取数据, 返回结果中 caseOwnOrgAncestors 属性为案属机构祖先 id 数组
     * @return R<CaseEventVO>
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasAnyPermission('CaseGet')")
    public R<CaseEventVO> getById(@PathVariable("id") String id, Boolean forEdit) {
        CaseEventVO cevo = caseEventService.getCaseVOById(id);
        if ((forEdit != null) && (forEdit)) {
            System.out.println(String.format("getById forEdit=%s", forEdit));
            R<List<String>> rOrg = remoteOrgService.getAncestorids(cevo.getCaseOwnOrgId());
            cevo.setCaseOwnOrgAncestors(rOrg.getData());
            System.out.println(String.format("getById forEdit=%s getAncestorids=", forEdit, rOrg));
        }

        Entrustment one = entrustmentService.getOne(Wrappers.<Entrustment>lambdaQuery().eq(Entrustment::getCaseId, id));
        String entrustId = one.getId();
        cevo.setSuspects(suspectService.list(Wrappers.<Suspect>lambdaQuery().eq(Suspect::getEntrustId, entrustId)));
        cevo.setEntrustmentType(one.getEntrustmentType());
        cevo.setOldIdentificationResult(one.getOldIdentificationResult());
        return R.ok(cevo);
    }

//	/**
//     * 分页查询
//     * @param page 分页对象
//     * @param caseEvent 案件事件
//     * @return
//     */
//    @ApiOperation(value = "分页查询", notes = "分页查询")
//    @GetMapping("/page" )
//    public R getCaseEventPage(Page page, CaseEvent caseEvent) {
//		System.out.println(String.format("getCaseEventPage, caseEvent=%s", caseEvent.toString()));
//	    return R.ok(caseEventService.page(page, Wrappers.<CaseEvent>query()
//	    ));
//    }

    /**
     * 分页查询
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseName
     * @param caseType
     * @return R<IPage < CaseEventVO>>
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasAnyPermission('CaseList')")
    public R<IPage<CaseEventVO>> getCaseEventPage(Page page, String fromDate, String toDate, String caseName, String caseType, String orgId, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if (!dlpUser.isStaff()) {
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件
        }

        System.out.println(String.format("getCaseEventPage, fromDate=%s, toDate=%s, caseName=%s, caseType=%s", fromDate, toDate, caseName, caseType));
        IPage<CaseEventVO> thePage = caseEventService.getCaseVoPage(page, Wrappers.<CaseEvent>query()
                .like(StrUtil.isNotBlank(caseName), "cj.case_name", caseName)
                .eq(StrUtil.isNotBlank(caseType), "cj.case_type", caseType)
                //.eq(StrUtil.isNotBlank(criminalType), "cj.criminal_type", criminalType)
                .eq(StrUtil.isNotBlank(orgId), "cj.case_own_org_id", orgId)
                .ge(StrUtil.isNotBlank(fromDate), "cj.happen_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "cj.happen_time", toDate)
                .orderByDesc("create_time") //按创建时间降序排序
        );
        R<IPage<CaseEventVO>> r = R.ok(thePage);
        return r;
    }

//	@GetMapping("/list" )
//	//@PreAuthorize("@pms.hasPermission('entrustment_caseevent_get')" )
//	public R getCaseEventVOList(String fromDate, String toDate, String caseName, String caseType, String criminalType) {
//		System.out.println(String.format("getCaseEventVOList, fromDate=%s, toDate=%s, caseName=%s, caseType=%s, criminalType=%s", fromDate, toDate, caseName, caseType, criminalType));
//		return R.ok(caseEventService.getCaseVoList(fromDate, toDate, caseName, caseType, criminalType));
//	}
//

    /**
     * 新增案件事件
     *
     * @param caseEvent 案件事件
     * @return R
     */
    @ApiOperation(value = "新增案件事件", notes = "新增案件事件。案件名称是必填项; 案件 id 不需要, 由系统自动生成; 案件编号 caseNo 依赖于案件所属单位和案发日期, 如果提供了这两个属性, 系统会自动生成案件编号")
    @SysLog("新增案件、事件")
    @PostMapping
    @PreAuthorize("@pms.hasAnyPermission('CaseCreate')")
    public R postAddObject(@RequestBody CaseEvent caseEvent, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if (StrUtil.isEmpty(caseEvent.getCaseName())) {
            return R.failed("案件名称不能为空!");
        }
        if (StrUtil.isBlank(caseEvent.getCaseOwnOrgId())) {
            caseEvent.setCaseOwnOrgId(dlpUser.getOrgId());  // 设置案件所属机构为用户所属机构, 即使是鉴定中心员工代录, 也先设置为鉴定中心
        } else {
            if (!dlpUser.isStaff()) {
                if (!StrUtil.equalsIgnoreCase(caseEvent.getCaseOwnOrgId(), dlpUser.getOrgId())) {
                    return R.failed("案件所属单位必须是你所属单位!");
                }
            }
        }
        if (caseEventService.postAddObject(caseEvent)) {
            return R.ok(caseEvent, "新增案件成功");
        } else {
            return R.failed(caseEvent, "新增案件失败");
        }
    }

    /**
     * 修改案件事件
     *
     * @param dto 案件事件
     * @return R
     */
    @ApiOperation(value = "修改案件事件", notes = "修改案件事件")
    @SysLog("修改案件事件")
    @PutMapping
    @PreAuthorize("@pms.hasAnyPermission('CaseEdit')")
    public R putUpdateById(@RequestBody UpdateCaseAndEntrustTypeDTO dto, HttpServletRequest theHttpServletRequest) {
        if (StrUtil.isBlank(dto.getId())) {
            return R.failed(dto, "id 不能为空!");
        }
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if (!dlpUser.isStaff()) {
            // 不是鉴定中心员工, 检查一下案件所属机构与用户是不是同一机构
            CaseEvent oldCase = caseEventService.getById(dto.getId());
            if (oldCase == null || StrUtil.isBlank(oldCase.getCaseOwnOrgId()) || (!StrUtil.equalsIgnoreCase(oldCase.getCaseOwnOrgId(), dlpUser.getOrgId()))) {
                return R.failed(dto, "只能修改自己单位的案件!");
            }
        }

        if (StrUtil.isEmpty(dto.getCaseName())) {
            return R.failed(dto, "案件名称不能为空!");
        }

        if (StrUtil.isBlank(dto.getCaseNo())) {
            // 如果没有提供案件编码, 生成一个

            if ((dto.getHappenTime() != null) && (StrUtil.isNotBlank(dto.getCaseOwnOrgId()))) {
                SysOrg caseOwnOrg = null;
                R r = remoteOrgService.getById(dto.getCaseOwnOrgId());
                if (r.getCode() == CommonConstants.SUCCESS) {
                    caseOwnOrg = (SysOrg) r.getData();

//                    Date happenTime = Date.from(caseEvent.getHappenTime().atZone(ZoneId.systemDefault()).toInstant());

                    dto.setCaseNo(caseEventService.getNewCaseCode(caseOwnOrg.getOrgCode(), dto.getHappenTime()));
                } else {
                    return R.failed(String.format("没有找到 orgId 为 %s 的机构, 请确认案件所属机构(CaseOwnOrg)的正确性!", dto.getCaseOwnOrgId()));
                }
            }
        }
        CaseEvent caseEvent = CaseEventConvert.dtoToEntity(dto);
        if (caseEventService.updateById(caseEvent)) {
            // 判断委托需要更新不
            if (ObjectUtil.isNotNull(dto.getEntrustmentType())) {
                entrustmentService.update(Wrappers.<Entrustment>lambdaUpdate()
                        .eq(Entrustment::getId, dto.getEntrustId())
                        .set(Entrustment::getEntrustmentType, dto.getEntrustmentType())
                        .set(StrUtil.isNotBlank(dto.getOldIdentificationResult()), Entrustment::getOldIdentificationResult, dto.getOldIdentificationResult())
                );
            }
            Entrustment entrustment = entrustmentService.getById(dto.getEntrustId());
            if (entrustment.getEntrustmentType() == 1) {

            }
            if (entrustment.getEntrustmentType() == 1 && (dto.getSuspects() == null || dto.getSuspects().isEmpty())) {
                throw new RuntimeException("生物样本案件必须提供嫌疑人信息!");
            }

            if (ObjectUtil.isNotEmpty(dto.getSuspects())) {
                List<Suspect> oldList = suspectService.list(Wrappers.<Suspect>lambdaQuery().eq(Suspect::getEntrustId, dto.getEntrustId()));
                suspectService.addSuspectList(dto.getSuspects(), dto.getEntrustId());
                if (oldList != null && !oldList.isEmpty()) {
                    suspectService.removeBatchByIds(oldList.stream().map(Suspect::getId).collect(Collectors.toList()));
                }
            }

            return R.ok(caseEvent, "保存案件信息成功");
        } else {
            return R.failed(caseEvent, "保存案件信息失败");
        }
    }

    /**
     * 通过id删除案件事件
     * 删除案件的前提是这个案件相关的委托从未提交过, 或根本就没有委托
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除案件事件", notes = "通过id删除案件事件")
    @SysLog("通过id删除案件事件")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasAnyPermission('CaseDelete')")
    public R deleteById(@PathVariable String id, HttpServletRequest theHttpServletRequest) throws Exception {
        if (StrUtil.isBlank(id)) {
            return R.failed("必须把 caseId 作为路径的一部分提供!");
        }
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        CaseEvent ce = caseEventService.deleteById(id, dlpUser);

        if (ce != null) {
            return R.ok(ce, "案件删除成功");
        } else {
            return R.failed(ce, "案件删除失败");
        }
    }

    /**
     * 取指定案件的附件列表
     *
     * @param caseId
     * @return
     */
    @GetMapping("/attachment/{caseId}/list")
    @PreAuthorize("@pms.hasAnyPermission('CaseAttachmentList')")
    public R getAttachmentList(@PathVariable("caseId") String caseId) {
        CaseEvent cj = caseEventService.getById(caseId);
        if (cj != null) {
            return R.ok(ossFile.fileList(OSSDirectoryConstants.CASE_DIRECTORY + "/" + caseId));
        }
        return R.failed("不存在这个案件");
    }

    /**
     * 取指定案件的指定附件
     *
     * @param caseId
     * @param fileName
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/attachment/{caseId}/{fileName}")
    @PreAuthorize("@pms.hasAnyPermission('CaseAttachmentDownload')")
    public void getAttachmentObj(@PathVariable("caseId") String caseId, @PathVariable String fileName, HttpServletResponse httpServletResponse) throws Exception {
        CaseEvent cj = caseEventService.getById(caseId);
        if (cj != null) {
            try {
                ossFile.fileGet(OSSDirectoryConstants.CASE_DIRECTORY + "/" + caseId + "/" + fileName, httpServletResponse.getOutputStream());
                httpServletResponse.setContentType(new MimetypesFileTypeMap().getContentType(fileName));
            } catch (AmazonS3Exception s3e) {
                httpServletResponse.sendError(s3e.getStatusCode(), s3e.toString());
            } catch (Exception e) {
                httpServletResponse.sendError(501, e.toString());
            }
        } else {
            httpServletResponse.sendError(404, "不存在这个案件");
        }

    }

    @PostMapping(value = "/attachment/{caseId}")
    @PreAuthorize("@pms.hasAnyPermission('CaseAttachmentUpload')")
    public R uploadAttachmentObj(@PathVariable("caseId") String caseId, @RequestPart("file") MultipartFile file) throws Exception {
        System.out.println(String.format("uploadPhotoObj: caseId=%s OriginalFilename=%s", caseId, file.getOriginalFilename()));
        CaseEvent cj = caseEventService.getById(caseId);
        if (cj != null) {
            String path = OSSDirectoryConstants.CASE_DIRECTORY + "/" + caseId;
            boolean r = ossFile.fileUpload(file, path);

            Map<String, String> ResultData = new HashMap<>();
            ResultData.put("fileName", FileNameUtil.getName(file.getOriginalFilename()));
            ResultData.put("path", path);

            if (r) {
                return R.ok(ResultData, "上传成功");
            }
            return R.failed(ResultData, "上传失败");
        } else {
            return R.failed("不存在这个案件");
        }
    }

    @PostMapping(value = "/attachment_base64/{caseId}")
    @PreAuthorize("@pms.hasAnyPermission('CaseAttachmentUpload')")
    public R uploadAttachmentObj_Base64(@PathVariable("caseId") String caseId, @RequestBody JSONObject jsonParam) throws Exception {
        System.out.println(String.format("uploadPhotoObj: caseId=%s jsonParam.size()=%d", caseId, jsonParam.size()));
        CaseEvent cj = caseEventService.getById(caseId);
        if (cj != null) {

            String image = jsonParam.getString("image");
            //System.out.println(String.format("image=%s", image));
            if (StringUtils.isNotEmpty(image)) {
                try {
                    String suffix = image.substring(11, image.indexOf(";"));
                    String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "." + suffix;
                    System.out.println(String.format("fileName=[%s]", fileName));

                    //去掉头信息
                    String imgBase64 = image.substring(image.indexOf(",") + 1);
                    byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(imgBase64);
                    InputStream is = new ByteArrayInputStream(decoded);

                    String path = OSSDirectoryConstants.CASE_DIRECTORY + "/" + caseId;

                    Map<String, String> ResultData = new HashMap<>();
                    ResultData.put("fileName", fileName);
                    ResultData.put("path", path);

                    boolean r = ossFile.fileSave(path + "/" + fileName, is);
                    if (r) {
                        return R.ok(ResultData, "上传成功");
                    }
                    return R.failed("上传失败");

                } catch (Exception e) {
                    e.printStackTrace();
                    return R.failed("上传失败");
                }
            } else {
                return R.failed("上传的数据中没有图像");
            }

        }
        return R.failed("不存在这个案件");
    }


    @DeleteMapping("/attachment/{caseId}/{fileName}")
    @PreAuthorize("@pms.hasAnyPermission('CaseAttachmentDelete')")
    public R deleteAttachmentObj(@PathVariable("caseId") String caseId, @PathVariable String fileName) throws Exception {
        CaseEvent cj = caseEventService.getById(caseId);
        if (cj != null) {
            ossFile.fileDelete(OSSDirectoryConstants.CASE_DIRECTORY + "/" + caseId + "/" + fileName);
            Map<String, String> ResultData = new HashMap<>();
            ResultData.put("fileName", fileName);
            return R.ok(ResultData, "删除文件成功");
        }
        return R.failed("不存在这个案件");
    }

    //=====================================================================================

    /**
     * 通过id删除案件事件, 仅供测试使用, 允许级联删除: 案件/物证/委托/检材/样本
     * 删除案件的前提是这个案件相关的委托从未提交过, 或根本就没有委托
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除案件事件", notes = "通过id删除案件事件")
    @SysLog("通过id删除案件事件")
    @DeleteMapping("/admin/{id}")
    @PreAuthorize("@pms.hasAnyPermission('CaseAdmin')")
    public R test_deleteById(@PathVariable String id, HttpServletRequest theHttpServletRequest) throws Exception {
        if (StrUtil.isBlank(id)) {
            return R.failed("必须把 caseId 作为路径的一部分提供!");
        }
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        CaseEvent ce = caseEventService.getById(id);
        if (ce == null) {
            return R.failed(String.format("不存在 caseId 为 %s 的案件!", id));
        }

        if (!dlpUser.isStaff()) {
            // 不是鉴定中心员工, 检查一下案件所属机构与用户是不是同一机构
            if (StrUtil.isBlank(ce.getCaseOwnOrgId()) || (!StrUtil.equalsIgnoreCase(ce.getCaseOwnOrgId(), dlpUser.getOrgId()))) {
                return R.failed("只能删除自己单位的案件!");
            }
        }

        List<Entrustment> entrustmentList = entrustmentService.list(Wrappers.<Entrustment>query()
                .eq("case_id", id)
        );
        // for (Entrustment e : entrustmentList) {
        // 	if (StrUtil.isNotBlank(e.getProcessInstanceId())) {
        // 		return R.failed(String.format("这个案件的委托 %s 已经提交过, 不能删除!", e.getEntrustmentNo()));
        // 	}
        // }

        //--- 到这里, 没有委托或者所有委托都没有提交过, 原则上可删除这个案件 ---
        // 我们要按顺序删除案件相关的东西

        for (Entrustment e : entrustmentList) {
            // 删除全部检材
            List<EntrustmentIdentificationMaterial> eimList = entrustmentIdentificationMaterialService.list(Wrappers.<EntrustmentIdentificationMaterial>query().eq("entrustment_id", e.getId()));
            for (EntrustmentIdentificationMaterial eim : eimList) {
                // 删除检材的全部附件
                List<String> attList = ossFile.fileList(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + eim.getEntrustmentId() + "/" + eim.getId());
                for (String attName : attList) {
                    ossFile.fileDelete(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + eim.getEntrustmentId() + "/" + eim.getId() + "/" + attName);
                }
                // 删除检材本身
                entrustmentIdentificationMaterialService.removeById(eim.getId());
            }

            // 删除委托的全部附件
            List<String> attList = ossFile.fileList(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + e.getId());
            for (String attName : attList) {
                ossFile.fileDelete(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + e.getId() + "/" + attName);
            }

            // 删除委托本身
            entrustmentService.removeById(e.getId());
        }

        // 删除全部物证
        List<CaseEvidence> evidenceList = caseEvidenceService.list(Wrappers.<CaseEvidence>query().eq("case_id", id));
        for (CaseEvidence evidence : evidenceList) {
            // 删除物证的全部附件
            List<String> attList = ossFile.fileList(OSSDirectoryConstants.CASE_DIRECTORY + "/" + evidence.getCaseId() + "/" + evidence.getId());
            for (String attName : attList) {
                ossFile.fileDelete(OSSDirectoryConstants.CASE_DIRECTORY + "/" + evidence.getCaseId() + "/" + evidence.getId() + "/" + attName);
            }
            // 删除物证本身
            caseEvidenceService.removeById(evidence.getId());
        }
        // 删除案件的全部附件
        List<String> attList = ossFile.fileList(OSSDirectoryConstants.CASE_DIRECTORY + "/" + id);
        for (String attName : attList) {
            ossFile.fileDelete(OSSDirectoryConstants.CASE_DIRECTORY + "/" + id + "/" + attName);
        }

        if (caseEventService.removeById(id)) {
            return R.ok(ce, "案件删除成功");
        } else {
            return R.failed(ce, "案件删除失败");
        }
    }


    // 获取公安部禁毒大数据平台的数据同步到系统
    @ApiOperation(value = "获取公安部禁毒大数据平台的数据同步到系统", notes = "接口格式\n" +
            "{\n" +
            "  \"statusCode\": \"SUCCESS\",\n" +
            "  \"result\": {\n" +
            "    \"pageCount\": \"1\",\n" +
            "    \"recordCount\": \"2\",\n" +
            "    \"list\": [\n" +
            "      {\n" +
            "        \"id\": \"cGwrMERuWW50UXhjZEJzaERkaEgzbjNFU09jQi9DWU4=\",\n" +
            "        \"entrustSerialNumber\": \"WT-2023-0001\",\n" +
            "        \"status\": \"toAccept\",\n" +
            "        \"submitTime\": \"2023-05-26 16:02:58\",\n" +
            "        \"acceptTime\": \"\",\n" +
            "        \"finishTime\": \"\",\n" +
            "        \"entrustOrganization\": \"陕西省西安市新城区禁毒大队\",\n" +
            "        \"scheduledDate\": \"\",\n" +
            "        \"createUserDeptRegionCode\": \"610102\",\n" +
            "        \"caseName\": \"张三涉毒案\",\n" +
            "        \"materialType\": \"inVitro\",\n" +
            "        \"materialDescribe\": \"粉末2份，塑料袋包装\",\n" +
            "        \"entrustRequirement\": \"对1号检材中的海洛因进行定性分析，对2号检材中的甲基苯丙胺进行定性分析\",\n" +
            "        \"reportSendType\": \"takeFromOneself\",\n" +
            "        \"analysisStartTime\": \"\",\n" +
            "        \"analysisEndTime\": \"\",\n" +
            "        \"userList\": [\n" +
            "          {\n" +
            "            \"name\": \"赵小辉\",\n" +
            "            \"position\": \"科员\",\n" +
            "            \"cardType\": \"policeOfficerCard\",\n" +
            "            \"certificatesCode\": \"001223\",\n" +
            "            \"phone\": \"13965368974\"\n" +
            "          },\n" +
            "          {\n" +
            "            \"name\": \"吴晓辉\",\n" +
            "            \"position\": \"科员\",\n" +
            "            \"cardType\": \"policeOfficerCard\",\n" +
            "            \"certificatesCode\": \"001224\",\n" +
            "            \"phone\": \"13789562314\"\n" +
            "          }\n" +
            "        ],\n" +
            "        \"materialList\": [\n" +
            "          {\n" +
            "            \"index\": 1,\n" +
            "            \"name\": \"白色颗粒可疑物\",\n" +
            "            \"colorType\": \"白色\",\n" +
            "            \"shapeType\": \"粉末\",\n" +
            "            \"packageType\": \"塑料袋\",\n" +
            "            \"amount\": 1,\n" +
            "            \"unit\": \"gram\",\n" +
            "            \"targetObjectTypeList\": [\n" +
            "              \"海洛因\"\n" +
            "            ],\n" +
            "            \"analysisType\": \"qualitative\"\n" +
            "          },\n" +
            "          {\n" +
            "            \"index\": 2,\n" +
            "            \"name\": \"黄色颗粒可疑物\",\n" +
            "            \"colorType\": \"黄色\",\n" +
            "            \"shapeType\": \"粉末\",\n" +
            "            \"packageType\": \"塑料袋\",\n" +
            "            \"amount\": 1,\n" +
            "            \"unit\": \"gram\",\n" +
            "            \"targetObjectTypeList\": [\n" +
            "              \"甲基苯丙胺\"\n" +
            "            ],\n" +
            "            \"analysisType\": \"qualitative\"\n" +
            "          }\n" +
            "        ],\n" +
            "        \"analyseRecordList\": []\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"bk8wMFYvdmdXWlg4SE84amlFQThJbzhHZWdqeDNKeUQ=\",\n" +
            "        \"status\": \"created\",\n" +
            "        \"submitTime\": \"\",\n" +
            "        \"acceptTime\": \"\",\n" +
            "        \"finishTime\": \"\",\n" +
            "        \"entrustOrganization\": \"陕西省西安市新城区禁毒大队\",\n" +
            "        \"scheduledDate\": \"\",\n" +
            "        \"createUserDeptRegionCode\": \"610102\",\n" +
            "        \"caseName\": \"王翔涉毒案\",\n" +
            "        \"materialDescribe\": \"粉末1份、块状固体1份，塑料袋包装，液体1份，塑料瓶包装\",\n" +
            "        \"entrustRequirement\": \"对1号检材中的甲基苯丙胺、海洛因进行定性、定量分析，对2号检材中的氯胺酮进行定性分析，对3号检材中的氯胺酮进行定量分析\",\n" +
            "        \"reportSendType\": \"takeFromOneself\",\n" +
            "        \"analysisStartTime\": \"\",\n" +
            "        \"analysisEndTime\": \"\",\n" +
            "        \"userList\": [\n" +
            "          {\n" +
            "            \"name\": \"刘1\",\n" +
            "            \"position\": \"科员\",\n" +
            "            \"cardType\": \"policeOfficerCard\",\n" +
            "            \"certificatesCode\": \"002366\",\n" +
            "            \"phone\": \"13723569874\"\n" +
            "          },\n" +
            "          {\n" +
            "            \"name\": \"刘2\",\n" +
            "            \"position\": \"科员\",\n" +
            "            \"cardType\": \"policeOfficerCard\",\n" +
            "            \"certificatesCode\": \"002367\",\n" +
            "            \"phone\": \"13652147896\"\n" +
            "          }\n" +
            "        ],\n" +
            "        \"materialList\": [\n" +
            "          {\n" +
            "            \"index\": 1,\n" +
            "            \"name\": \"白色粉末可疑物\",\n" +
            "            \"colorType\": \"白色\",\n" +
            "            \"shapeType\": \"粉末\",\n" +
            "            \"packageType\": \"塑料袋\",\n" +
            "            \"amount\": 1,\n" +
            "            \"unit\": \"gram\",\n" +
            "            \"targetObjectTypeList\": [\n" +
            "              \"甲基苯丙胺\",\n" +
            "              \"海洛因\"\n" +
            "            ],\n" +
            "            \"analysisType\": \"qualitativeAndRation\"\n" +
            "          },\n" +
            "          {\n" +
            "            \"index\": 2,\n" +
            "            \"name\": \"红色块状物\",\n" +
            "            \"colorType\": \"红色\",\n" +
            "            \"shapeType\": \"块状固体\",\n" +
            "            \"packageType\": \"塑料袋\",\n" +
            "            \"amount\": 10,\n" +
            "            \"unit\": \"gram\",\n" +
            "            \"targetObjectTypeList\": [\n" +
            "              \"氯胺酮\"\n" +
            "            ],\n" +
            "            \"analysisType\": \"qualitative\"\n" +
            "          },\n" +
            "          {\n" +
            "            \"index\": 3,\n" +
            "            \"name\": \"黄色不明物\",\n" +
            "            \"colorType\": \"黄色\",\n" +
            "            \"shapeType\": \"液体\",\n" +
            "            \"packageType\": \"塑料瓶\",\n" +
            "            \"amount\": 1,\n" +
            "            \"unit\": \"milliliter\",\n" +
            "            \"targetObjectTypeList\": [\n" +
            "              \"氯胺酮\"\n" +
            "            ],\n" +
            "            \"analysisType\": \"ration\"\n" +
            "          }\n" +
            "        ],\n" +
            "        \"analyseRecordList\": []\n" +
            "      }\n" +
            " ]\n" +
            " }\n" +
            "}\n" +
            "</pre>")
    @SysLog("同步案件信息数据到系统")
    @PostMapping("/syncInfo")
    public R syncCaseEventInfo(@RequestBody EntrustDataVo entrustDataVo) {

		/*JSONObject dataObj = jsonParam.getJSONObject("result");
		JSONArray dataObjDetailList = dataObj.getJSONArray("list");*/
        Map<String, List<Map<String, String>>> caseEvents = caseEventService.syncCaseEventInfo(entrustDataVo, null, true);
        return R.ok(caseEvents);
    }

    @ApiOperation(value = "检查案件是否能修改", notes = "检查案件是否能修改")
    @GetMapping("/checkCaseIsEnableModify")
    public R checkCaseIsEnableModify(String caseId) {
        return R.ok(caseEventService.checkCaseIsEnableModify(caseId), "获取数据成功");
    }


    //=====================================================================================
    // 测试, 创建 100 个案件
//    @GetMapping("/create100")
//    public R xxx_TestCreate100() {
//        for (int i = 0; i < 100; i++) {
//            CaseEvent cj = new CaseEvent();
//            cj.setId(IdWorker.get32UUID().toUpperCase());
//            String ownOrgId = "520100";
//            String ownOrgCode = "520100";
//            cj.setHappenTime(LocalDateTime.now());
//            cj.setCaseName("第" + i + "个测试案件");
//            cj.setCaseType(String.format("%d", RandomUtil.randomInt(1, 6)));
//            //cj.setCriminalType(String.format("%d",RandomUtil.randomInt(1, 5)*1000));
//            cj.setCaseArea(RandomUtil.randomNumbers(6));
//            cj.setCaseAddress(RandomUtil.randomString(100));
//            cj.setCaseOwnOrgId(ownOrgId);
//
//            // 如果没有提供案件编码, 生成一个
//            Date happenTime = Date.from(cj.getHappenTime().atZone(ZoneId.systemDefault()).toInstant());
//            ;
//            cj.setCaseNo(caseEventService.getNewCaseCode(ownOrgCode, happenTime));
//
//            if (caseEventService.save(cj)) {
//                System.out.println("新增案件成功");
//            } else {
//                System.out.println("新增案件失败");
//            }
//
//        }
//        return R.ok("100 of case ware Created");
//        /*this is new update*/
//    }

}
