package digital.laboratory.platform.entrustment.controller;

import cn.hutool.core.lang.Assert;
import com.amazonaws.services.s3.model.AmazonS3Exception;
// import com.jacob.activeX.ActiveXComponent;
// import com.jacob.com.ComThread;
// import com.jacob.com.Dispatch;
// import com.jacob.com.Variant;
import digital.laboratory.platform.common.feign.RemoteGenerateWordService;
import digital.laboratory.platform.common.feign.RemoteWord2PDFService;
import digital.laboratory.platform.sys.dto.entrustment.CommonIdDto;
import digital.laboratory.platform.entrustment.dto.EntrustmentDTO;
import digital.laboratory.platform.entrustment.entity.*;
import digital.laboratory.platform.entrustment.service.*;
import digital.laboratory.platform.sys.feign.*;
import digital.laboratory.platform.sys.vo.entrustment.MarkersVO;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.common.security.util.SecurityUtils;
import digital.laboratory.platform.entrustment.enums.EntrustmentStatusConstants;
import digital.laboratory.platform.entrustment.vo.CaseEventVO;
import digital.laboratory.platform.entrustment.vo.EntrustmentVO;
import digital.laboratory.platform.sys.entity.SysUser;
// import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
// import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
// import org.jodconverter.JodConverter;
// import org.jodconverter.LocalConverter;
// import org.jodconverter.document.DefaultDocumentFormatRegistry;
// import org.jodconverter.office.LocalOfficeManager;
// import org.jodconverter.office.OfficeException;
// import org.jodconverter.office.OfficeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
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.security.Principal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;


/**
 * 委托
 * =====================================================================================================================
 * 这个类与 ServiceImpl 类似乎功能差不多。我们原则上规定:
 * ServiceImpl 类的功能主要从技术角度考虑, 而 Controller 类主要从业务角度考虑。
 * ServiceImpl 类的功能主要是涉及 对应的类或表的 实体本身, 而 Controller 类则是综合的。
 * 例如, 进入到下一环节这个功能, 在 ServiceImpl 类中只考虑 Entrustment 本身的数据更新, Controller 类应该考虑更多的业务上的综合变化(如其他数据的变化)
 * <p>
 * 流程的管理被看作是 Entrustment 的一部分, 也在 ServiceImpl 处理。Controller 不用关心流程
 * =====================================================================================================================
 *
 * @author Zhang Xiaolong created at  2022-03-22
 * @describe 委托 前端控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/papp/entrustment/entrustment")
@Api(tags = "003-委托管理")
@SuppressWarnings("all")
public class EntrustmentController {
//	@Autowired
//	private final HttpServletRequest httpServletRequest;

    private final CaseEventService caseEventService;
    private final EntrustmentService entrustmentService;
    private final EntrustmentIdentificationMaterialService entrustmentIdentificationMaterialService;
    private final OssFile ossFile;
    private final IdentificationService identificationService;
    private final SampleService sampleService;
    private final RemoteDeliverService remoteDeliverService;
    private final RemoteUserService remoteUserService;
    private final RemoteOrgService remoteOrgService;
    private final RemoteWord2PDFService remoteWord2PDFService;
    private final RemoteSampleService remoteSampleService;//流转系统的feign 接口
    private final RemoteDictionaryService remoteDictionaryService;//字典接口

    private final SynchronizeDataService synchronizeDataService;//同步数据服务接口

    private final RemoteGenerateWordService remoteGenerateWordService;
    //private  final  RestTemplate restTemplate;

//	/**
//	 * 审核人员由委托创建者选择。如果 true, 前台在委托提交审核前, 弹出界面让委托人选择审核者; 如果 false, 由系统自动选择审核者。
//	 * 如果 singleOperateUser 为 true, 表示只能有一个候选; singleOperateUser 为 false 表示可以有多个候选。
//	 * singleOperateUser 决定了委托人选择审核者时是单选还是多选, 如果由系统自动选, 有多个待选用户时, 随机选择一个
//	 */

    /**
     * 通过id查询委托
     *
     * @param id      id
     * @param forEdit 如果为true, 表示为编辑而取数据, 返回结果中 clientOrgAncestors 属性为机构祖先 id 数组
     * @return R<EntrustmentVO>
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('EntrustmentGet')")
    public R<EntrustmentVO> bizGetEntrustmentById(@PathVariable("id") String id, Boolean forEdit) {
        EntrustmentVO evo = entrustmentService.getEntrustmentVOById(id);
        if ((forEdit != null) && (forEdit)) {
            R<List<String>> rOrg = remoteOrgService.getAncestorids(evo.getClientOrgId());
            evo.setClientOrgAncestors(rOrg.getData());
        }
        return R.ok(evo);
    }


    /**
     * 分页查询
     * <p>
     * 分页查询按岗位划分为 6 个函数(或更多), 并且额外提供一个汇总入口
     * <p>
     * 从操作人员的情况来看, 主要有两种:
     * - 作为普通用户, 只能看到自己是提交者(submitter)的委托; 还有送检确认, 是委托单位的领导, 应该可以目的地该机构下的所有委托
     * - 作为鉴定中心员工, 可以看到所有委托
     * <p>
     * 根据用户的岗位, 有多种场景; 对每一个岗位, 主要有两种情况(操作前和操作后)
     * - 作为委托创建者(创建、修改、提交), 可以看到提交前: 自己创建(createBy/updateBy)的委托, 提交后: 提交人是自己的委托
     * - 作为审核者, 已提交待审核: 候选人中包含自己的委托; 已审核: 审核人是自己的委托
     * - 作为审批者, 已审核待审批: 候选人中包含自己的委托; 已审批: 审批人是自己的委托
     * - 作为送检确认者, 待确认: 已审批的委托; 已确认: 确认人是自己的委托
     * - 作为送检提交(委托), 待送检: 已确认并且审核提交人是自己; 已送检: 送检提交人是自己
     * - 作为受理人, 待受理: 所有已送检待受理; 已受理: 受理人是自己
     * <p>
     * 查询条件:
     * - 时间, 在某个时间范围内查询
     * - 案件ID/案件名(模糊查)
     * - 状态:
     * * 待提交, 委托单位工作人员会看
     * * 待审核, 委托单位、审核人员会看
     * * 待审批, 委托单位、审核人员、审批人员会看
     * * 待确认, 委托单位、审核人员、审批人员、确认人员会看
     * * 待送检, 委托单位、审核人员、审批人员、确认人员会看
     * * 待受理, 委托单位、审核人员、审批人员、确认人员、受理人员会看
     *
     * @param page     分页对象
     * @param fromDate 开始日期
     * @param toDate   结束日期
     * @param caseId   案件ID
     * @param caseName 案件名称(模糊查询)
     * @param statuses 状态列表(多个状态)
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage00(Page<Entrustment> page,
                                                           @RequestParam(value = "keyword", required = false) String keyword,
                                                           @RequestParam(value = "fromDate", required = false) String fromDate,
                                                           @RequestParam(value = "toDate", required = false) String toDate,
                                                           @RequestParam(value = "caseId", required = false) String caseId,
                                                           @RequestParam(value = "caseName", required = false) String caseName,
                                                           @RequestParam(value = "statuses", required = false) List<Integer> statuses,
                                                           @RequestParam(value = "submitter", required = false) String submitter,
                                                           @RequestParam(value = "checkCandidateUser", required = false) String checkCandidateUser,
                                                           @RequestParam(value = "checkUser", required = false) String checkUser,
                                                           @RequestParam(value = "dataSources", required = false) Integer dataSources) {
        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("getEntrustmentPage 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));
        if (StrUtil.isNotBlank(keyword)) {
            keyword = keyword.trim();
        }
        final String theKeyword = keyword;

        IPage<EntrustmentVO> thePage = null;
        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            Boolean test1 = (statuses != null) && (statuses.size() > 0);
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .and(StrUtil.isNotBlank(theKeyword), wrapper -> wrapper
                            .like("e.entrustment_no", theKeyword)
                            .or()
                            .like("e.client_org_name", theKeyword)
                            .or()
                            .like("e.accept_no", theKeyword)
                            .or()
                            .like("c.case_name", theKeyword))
                    .eq(StrUtil.isNotBlank(checkCandidateUser), "e.checkCandidateUser", checkCandidateUser)
                    .ge(StrUtil.isNotBlank(fromDate), "e.submit_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.submit_time", toDate)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .in((statuses != null) && (statuses.size() > 0), "e.status", statuses)
                    .eq(dataSources != null, "e.data_sources", dataSources)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .orderByDesc(statuses != null && statuses.size() > 0 && statuses.get(0) == 9, "CAST(SUBSTRING(e.accept_no, 1,4) AS UNSIGNED)","CAST(SUBSTRING(e.accept_no, 6) AS UNSIGNED)")
                    .orderByDesc(statuses != null && statuses.size() > 0 && statuses.get(0) == 7, "CAST(SUBSTRING(e.entrustment_no, 4,4) AS UNSIGNED)","CAST(SUBSTRING(e.entrustment_no, 9) AS UNSIGNED)")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq(!dlpUser.isStaff(), "e.submitter", dlpUser.getId())
                    .eq("e.client_org_id", orgId)
                    .ge(StrUtil.isNotBlank(fromDate), "e.submit_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.submit_time", toDate)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    //.in((statuses != null) && (statuses.size() > 0), "e.status", new HashSet<Integer>(statuses))
                    .in((statuses != null) && (statuses.size() > 0), "e.status", statuses)
            );

        }

        return R.ok(thePage);

//		return R.ok(entrustmentService.page(page, Wrappers.query(entrustment)));
    }

    /**
     * 00
     * 分页查询 - 委托提交者 - 委托提交前
     * <p>
     * 以委托提交者身份查看委托提交前
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托提交者身份查看委托提交前", notes = "分页查询, 以委托提交者身份查看委托提交前")
    @GetMapping("/page_submitter_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage01_Submitter_Before(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentPage_Submitter_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.create_by", dlpUser.getId())
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                    .orderByDesc("e.create_time")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.create_by", dlpUser.getId())
                    .eq("e.client_org_id", orgId)
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                    .orderByDesc("e.create_time")
            );
        }

        return R.ok(thePage);
    }


    /**
     * 统计 - 委托提交者 - 委托提交前的委托数量
     * <p>
     * 以委托提交者身份查看委托提交前的委托数量
     *
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "统计, 以委托提交者身份查看委托提交前的委托数量", notes = "统计, 以委托提交者身份查看委托提交前的委托数量")
    @GetMapping("/count_submitter_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public long bizGetEntrustmentCount_Submitter(String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentCount_Submitter 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            return entrustmentService.count(Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.create_by", dlpUser.getId())
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            return entrustmentService.count(Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.create_by", dlpUser.getId())
                    .eq("e.client_org_id", orgId)
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
            );
        }

    }

    /**
     * 分页查询 - 委托提交者 - 委托提交后
     * <p>
     * 以委托提交者身份查看委托提交后
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托提交者身份查看委托提交后", notes = "分页查询, 以委托提交者身份查看委托提交后")
    @GetMapping("/page_submitter_after")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage02_Submitter_After(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentPage02_Submitter_After 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    //.ne("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                    .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                    .orderByDesc("e.submit_time")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
                    .eq("e.client_org_id", orgId)
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .ne("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                    .orderByDesc("e.submit_time")
            );
        }

        return R.ok(thePage);
    }


    /**
     * 分页查询 - 审核者 - 委托审核前
     * <p>
     * 以委托审核者身份查看委托审核前
     * <p>
     * checker: BC1A096180973C5EA652C9787F5A155A,C27B8F582693B93596C21C1586A0845A
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托审核者身份查看委托审核前", notes = "分页查询, 以委托审核者身份查看委托审核前")
    @GetMapping("/page_checker_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentCheck')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage03_Checker_Before(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne, Integer dataSources) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            throw new RuntimeException("审核员必须是鉴定中心员工, 普通用户不能对委托进行审核。");
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentPage03_Checker_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .like(StrUtil.isNotBlank(caseName), "e.entrustment_no", caseName)//因为未提供扫码查询，所有只能这样改
                .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                .eq(dataSources != null, "e.data_sources", dataSources)
                .and((wrapper) -> wrapper
                        .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK_CLAIM.getStatus())
                        .or()
                        .like((includeOtherOne == null || !includeOtherOne), "e.check_candidate_user", dlpUser.getId())
                        .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK.getStatus())
                )
                // .like((includeOtherOne == null || !includeOtherOne), "e.check_candidate_user", dlpUser.getId())
                // .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK_CLAIM.getStatus(), EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK.getStatus())
                .orderByDesc("e.submit_time")
        );

        return R.ok(thePage);
    }


    /**
     * 统计 - 审核者 - 委托审核前的委托数量
     * <p>
     * 以委托审核者身份查看委托审核前的委托数量
     * <p>
     * checker: BC1A096180973C5EA652C9787F5A155A,C27B8F582693B93596C21C1586A0845A
     *
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "统计, 以委托审核者身份查看委托审核前的委托数量", notes = "统计, 以委托审核者身份查看委托审核前的委托数量")
    @GetMapping("/count_checker_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentCheck')")
    public long bizGetEntrustmentCount_Checker(String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            return 0;
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentCount_Checker 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        return entrustmentService.count(Wrappers.<Entrustment>query()
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                .and((wrapper) -> wrapper
                        .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK_CLAIM.getStatus())
                        .or()
                        .like((includeOtherOne == null || !includeOtherOne), "e.check_candidate_user", dlpUser.getId())
                        .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK.getStatus())

                )
        );

    }

    /**
     * 分页查询 - 审核者 - 委托审核后
     * <p>
     * 以委托审核者身份查看委托审核后
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托审核者身份查看委托审核后", notes = "分页查询, 以委托审核者身份查看委托审核后")
    @GetMapping("/page_checker_after")
    @PreAuthorize("@pms.hasPermission('EntrustmentCheck')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage04_Checker_After(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            throw new RuntimeException("审核员必须是鉴定中心员工, 普通用户不能对委托进行审核。");
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentPage04_Checker_After 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                .eq((includeOtherOne == null || !includeOtherOne), "e.check_user", dlpUser.getId())
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK.getStatus())    // 状态为审核之后
                .orderByDesc("e.check_time")
        );

        return R.ok(thePage);
    }


    /**
     * 分页查询 - 审批者 - 委托审批前
     * <p>
     * 以委托审批者身份查看委托审批前
     * <p>
     * approver: 104C88AFF30A71DE230A82C8C34F8F57,009D54E9C222702659733CBE9C381108
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托审批者身份查看委托审批前", notes = "分页查询, 以委托审批者身份查看委托审批前")
    @GetMapping("/page_approver_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentApprove')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage05_Approver_Before(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne, Integer dataSources) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            throw new RuntimeException("审核员必须是鉴定中心员工, 普通用户不能对委托进行审核。");
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentPage05_Approver_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                //.like((includeOtherOne == null || !includeOtherOne), "e.approve_candidate_user", dlpUser.getId())
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                .eq(dataSources != null, "e.data_sources", dataSources)
                .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_APPROVE_CLAIM.getStatus(), EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_APPROVE.getStatus())
                .orderByDesc("e.check_time")
        );

        return R.ok(thePage);
    }


    /**
     * 统计 - 审批者 - 委托审批前的委托数量
     * <p>
     * 以委托审批者身份查看委托审批前的委托数量
     * <p>
     * approver: 104C88AFF30A71DE230A82C8C34F8F57,009D54E9C222702659733CBE9C381108
     *
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "统计, 以委托审批者身份查看委托审批前的委托数量", notes = "统计, 以委托审批者身份查看委托审批前的委托数量")
    @GetMapping("/count_approver_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentApprove')")
    public long bizGetEntrustmentCount_Approver(String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            return 0;
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentPage05_Approver_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        return entrustmentService.count(Wrappers.<Entrustment>query()
                .like((includeOtherOne == null || !includeOtherOne), "e.approve_candidate_user", dlpUser.getId())
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_APPROVE_CLAIM.getStatus(), EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_APPROVE.getStatus())
        );

    }

    /**
     * 分页查询 - 审批者 - 委托审批后
     * <p>
     * 以委托审批者身份查看委托审批后
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托审批者身份查看委托审批后", notes = "分页查询, 以委托审批者身份查看委托审批后")
    @GetMapping("/page_approver_after")
    @PreAuthorize("@pms.hasPermission('EntrustmentApprove')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage06_Approver_After(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            throw new RuntimeException("审核员必须是鉴定中心员工, 普通用户不能对委托进行审核。");
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentPage06_Approver_After 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                .eq((includeOtherOne == null || !includeOtherOne), "e.approve_user", dlpUser.getId())
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_APPROVE.getStatus())    // 状态为审核之后
                .orderByDesc("e.approve_time")
        );

        return R.ok(thePage);
    }


    /**
     * 分页查询 - 送检确认者 - 委托送检确认前
     * <p>
     * 以委托送检确认者身份查看委托送检确认前
     * <p>
     * approver: 104C88AFF30A71DE230A82C8C34F8F57,009D54E9C222702659733CBE9C381108
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托送检确认者身份查看委托送检确认前", notes = "分页查询, 以委托送检确认者身份查看委托送检确认前")
    @GetMapping("/page_confirmer_before")
//	@PreAuthorize("@pms.hasPermission('EntrustmentConfirm') || @pms.hasPermission('EntrustmentAidInput')")
    @PreAuthorize("@pms.hasPermission('EntrustmentConfirm')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage07_Confirmer_Before(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentPage07_Confirmer_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CONFIRM.getStatus())
                            .orderByDesc("e.approve_time")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .eq("e.client_org_id", orgId)
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CONFIRM.getStatus())
                            .orderByDesc("e.approve_time")
            );
        }

        return R.ok(thePage);
    }


    /**
     * 统计 - 送检确认者 - 委托送检确认前的委托数量
     * <p>
     * 以委托送检确认者身份查看委托送检确认前的委托数量
     * <p>
     *
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "统计, 以委托送检确认者身份查看委托送检确认前的委托数量", notes = "统计, 以委托送检确认者身份查看委托送检确认前的委托数量")
    @GetMapping("/count_confirmer_before")
//	@PreAuthorize("@pms.hasPermission('EntrustmentConfirm') || @pms.hasPermission('EntrustmentAidInput')")
    @PreAuthorize("@pms.hasPermission('EntrustmentConfirm')")
    public long bizGetEntrustmentCount_Confirmer(String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentCount_Confirmer 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            return entrustmentService.count(Wrappers.<Entrustment>query()
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CONFIRM.getStatus())
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            return entrustmentService.count(Wrappers.<Entrustment>query()
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .eq("e.client_org_id", orgId)
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CONFIRM.getStatus())
            );
        }

    }

    /**
     * 分页查询 - 送检确认者 - 委托送检确认后
     * <p>
     * 以委托送检确认者身份查看委托送检确认后
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托送检确认者身份查看委托送检确认后", notes = "分页查询, 以委托送检确认者身份查看委托送检确认后")
    @GetMapping("/page_confirmer_after")
    //@PreAuthorize("@pms.hasPermission('EntrustmentConfirm') || @pms.hasPermission('EntrustmentAidInput')")
    @PreAuthorize("@pms.hasPermission('EntrustmentConfirm')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage08_Confirmer_After(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentPage08_Confirmer_After 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.submitter", dlpUser.getId())
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CONFIRM.getStatus())
                            .orderByDesc("e.deliver_confirm_time")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.submitter", dlpUser.getId())
                            .eq("e.client_org_id", orgId)
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CONFIRM.getStatus())
                            .orderByDesc("e.deliver_confirm_time")
            );
        }

        return R.ok(thePage);
    }


    /**
     * 分页查询 - 委托送检提交者 - 委托送检提交前
     * <p>
     * 以委托送检提交者身份查看委托送检提交前
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托送检提交者身份查看委托送检提交前", notes = "分页查询, 以委托送检提交者身份查看委托送检提交前")
    @GetMapping("/page_deliver_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage09_Deliver_Before(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentPage09_Deliver_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                            .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus())
                            .orderByDesc("e.deliver_confirm_time")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                            .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .eq("e.client_org_id", orgId)
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus())
                            .orderByDesc("e.deliver_confirm_time")
            );
        }

        return R.ok(thePage);
    }


    /**
     * 统计 - 委托送检提交者 - 委托送检提交前的委托数量
     * <p>
     * 以委托送检提交者身份查看委托送检提交前的委托数量
     *
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托送检提交者身份查看委托送检提交前", notes = "分页查询, 以委托送检提交者身份查看委托送检提交前")
    @GetMapping("/count_deliver_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public long bizGetEntrustmentCount_Deliver(String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentCount_Deliver 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            return entrustmentService.count(Wrappers.<Entrustment>query()
                            .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus())
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            return entrustmentService.count(Wrappers.<Entrustment>query()
                            .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
//					.eq((includeOtherOne==null || ! includeOtherOne ), "e.create_by", dlpUser.getId())
                            .eq("e.client_org_id", orgId)
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                            .eq("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus())
            );
        }
    }

    /**
     * 分页查询 - 委托送检提交者 - 委托送检提交后
     * <p>
     * 以委托送检提交者身份查看委托送检提交后
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托送检提交者身份查看委托送检提交后", notes = "分页查询, 以委托送检提交者身份查看委托送检提交后")
    @GetMapping("/page_deliver_after")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage10_Deliver_After(Page<Entrustment> page, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {

        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("bizGetEntrustmentPage10_Deliver_After 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        IPage<EntrustmentVO> thePage = null;

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus())
                    .orderByDesc("e.deliver_time")
            );
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq((includeOtherOne == null || !includeOtherOne), "e.submitter", dlpUser.getId())
                    .eq("e.client_org_id", orgId)
                    .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                    .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                    .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                    .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                    .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                    .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                    .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus())
                    .orderByDesc("e.deliver_time")
            );
        }

        return R.ok(thePage);
    }


    /**
     * 分页查询 - 受理员 - 委托受理前
     * <p>
     * 以委托受理员身份查看委托受理前
     * <p>
     * approver: 104C88AFF30A71DE230A82C8C34F8F57,009D54E9C222702659733CBE9C381108
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托受理员身份查看委托受理前", notes = "分页查询, 以委托受理员身份查看委托受理前")
    @GetMapping("/page_accepter_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage11_Accepter_Before(Page<Entrustment> page, String keyword, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne, Integer dataSources) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            throw new RuntimeException("受理员必须是鉴定中心员工, 普通用户不能对委托进行受理。");
        }
        if (StrUtil.isNotBlank(keyword)) {
            keyword = keyword.trim();
        }
        final String theKeyword = keyword;

        System.out.println(String.format("bizGetEntrustmentPage11_Accepter_Before 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        if (StrUtil.isNotBlank(theKeyword)) {
            // 有提供 keyword, 模糊查询

            // 先查是不是委托编号
            IPage<EntrustmentVO> thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq("e.entrustment_no", theKeyword)
                    .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus() /*, EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTING.getStatus()*/)
            );
            if (thePage.getRecords().size() > 0) {
                // 查到数据了, 直接返回
                return R.ok(thePage);
            }
        }

        IPage<EntrustmentVO> thePage = null;
        thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus() /*, EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTING.getStatus()*/)
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .eq(dataSources != null, "e.data_sources", dataSources)
                .and(StrUtil.isNotBlank(theKeyword), (wrapper) -> wrapper        // 如果 keyword 非空
                        .like("e.entrustment_no", theKeyword)
                        .or()
                        .like("e.case_id", theKeyword)
                        .or()
                        .like("c.case_no", theKeyword)
                        .or()
                        .like("c.case_name", theKeyword)
                )
                //.orderByDesc("e.deliver_time")
                .orderByDesc("e.entrustment_no")
        );

        return R.ok(thePage);
    }

    /**
     * 统计 - 受理员 - 委托受理前待受理数
     * <p>
     * 以委托受理员身份查看委托受理前待受理数
     * <p>
     *
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 0/1, false/true    是否看其他候选人的
     * @return
     */
    @ApiOperation(value = "统计, 以委托受理员身份查看委托受理前待受理数", notes = "统计, 以委托受理员身份查看委托受理前待受理数")
    @GetMapping("/count_accepter_before")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public long bizGetEntrustmentCount_with_Accepter(String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            return 0;
        }

        String orgId = null;
        System.out.println(String.format("bizGetEntrustmentCount_with_Accepter 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        long count = entrustmentService.count(Wrappers.<Entrustment>query()
//				.like((includeOtherOne==null || ! includeOtherOne ), "e.approve_candidate_user", dlpUser.getId())
                        .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                        .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                        .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                        .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                        .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                        .like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
                        .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus() /*, EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTING.getStatus()*/)
        );

        return count;
    }


    /**
     * 分页查询 - 受理员 - 委托受理后
     * <p>
     * 以委托受理员身份查看委托受理前
     *
     * @param page
     * @param fromDate
     * @param toDate
     * @param caseId
     * @param caseName
     * @param includeOtherOne 是否代录
     * @return
     */
    @ApiOperation(value = "分页查询, 以委托受理员身份查看委托受理前", notes = "分页查询, 以委托受理员身份查看委托受理前")
    @GetMapping("/page_accepter_after")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R<IPage<EntrustmentVO>> bizGetEntrustmentPage12_Accepter_After(Page<Entrustment> page, String keyword, String fromDate, String toDate, String entrustmentNo, String caseId, String caseNo, String caseName, Boolean includeOtherOne, Integer dataSources) {
        //-- 当前用户一定是鉴定中心员工, 普通用户没有审核权限
        DLPUser dlpUser = SecurityUtils.getUser();
        if (!dlpUser.isStaff()) {
            throw new RuntimeException("受理员必须是鉴定中心员工, 普通用户不能对委托进行受理。");
        }
        if (StrUtil.isNotBlank(keyword)) {
            keyword = keyword.trim();
        }

        System.out.println(String.format("bizGetEntrustmentPage12_Accepter_After 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));


        final String theKeyword = keyword;
        if (StrUtil.isNotBlank(theKeyword)) {
            // 有提供 keyword, 模糊查询

            // 先查是不是委托编号
            IPage<EntrustmentVO> thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                    .eq("e.entrustment_no", theKeyword)
                    .in("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus() /*, EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTING.getStatus()*/)
                    .orderByDesc("e.accept_time")
            );
            if (thePage.getRecords().size() > 0) {
                // 查到数据了, 直接返回
                return R.ok(thePage);
            }
        }

        IPage<EntrustmentVO> thePage = null;
        thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
                .gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus())    // 状态为审核之后
                .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                .eq(dataSources != null, "e.data_sources", dataSources)
                .and(StrUtil.isNotBlank(theKeyword), (wrapper) -> wrapper        // 如果 keyword 非空
                        .like("e.entrustment_no", theKeyword)
                        .or()
                        .like("e.case_id", theKeyword)
                        .or()
                        .like("c.case_no", theKeyword)
                        .or()
                        .like("c.case_name", theKeyword)
                )
                .orderByDesc("e.accept_time")
        );
/*
		IPage<EntrustmentVO> thePage = null;

		thePage = entrustmentService.getEntrustmentVOPage(page, Wrappers.<Entrustment>query()
//				.eq((includeOtherOne==null || ! includeOtherOne ), "e.approve_user", dlpUser.getId())
						.ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
						.le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
						.like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
						.eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
						.like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
						.like(StrUtil.isNotBlank(caseName), "c.case_name", caseName)
						.gt("e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus())    // 状态为审核之后
						.orderByDesc("e.accept_time")
		);
*/
        return R.ok(thePage);
    }

    /**
     * 查询案件的委托数量
     *
     * @param caseId 案件id
     * @return
     */
    @ApiOperation(value = "查询案件的委托数量", notes = "查询案件的委托数量")
    @GetMapping("/count")
    @PreAuthorize("@pms.hasAnyPermission('EntrustmentList')")
    public R getCaseEntrustmentCount(String caseId) {
        long count = entrustmentService.countByCaseId(caseId);
        Map<String, Long> ret = new HashMap<String, Long>();
        ret.put("count", count);
        return R.ok(count, "查询案件的委托数量成功");
    }

    /**
     * 委托创建者保存委托信息
     * 保存委托的以下属性:
     * client_org_name
     * client_address
     * client_postcode
     * client_tel
     * client_fax
     * identification_domain
     * identification_org_name
     * qualitative_analysis
     * quantitative_analysis
     * other_identification_requests
     * candidate_drugs
     * is_client_specified_method
     * client_specified_method
     * destructive_analysis
     * other_identification_notes
     * reidentification
     * old_identification_org_name
     * old_identification_document
     * old_identification_result
     * reidentification_reason
     * avoid_identifier
     * specified_identifier
     * other_agreement
     * report_receive_mode
     * sample_receive_mode
     * comments
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "委托创建者保存委托信息",
            notes = "委托创建者保存委托信息\n" +
                    "保存委托的以下属性:\n" +
                    "client_org_id(仅代录权限可以指定,其他用户系统指定为用户所属机构id)\n" +
                    "client_org_name\n" +
                    "client_address\n" +
                    "client_postcode\n" +
                    "client_tel\n" +
                    "client_fax\n" +
                    "identification_domain\n" +
                    "identification_org_name\n" +
                    "qualitative_analysis\n" +
                    "quantitative_analysis\n" +
                    "other_identification_requests\n" +
                    "candidate_drugs\n" +
                    "is_client_specified_method\n" +
                    "client_specified_method\n" +
                    "destructive_analysis\n" +
                    "other_identification_notes\n" +
                    "reidentification\n" +
                    "old_identification_org_name\n" +
                    "old_identification_document\n" +
                    "old_identification_result\n" +
                    "reidentification_reason\n" +
                    "avoid_identifier\n" +
                    "specified_identifier\n" +
                    "other_agreement\n" +
                    "identification_id\n" +
                    "report_receive_mode\n" +
                    "sample_receive_mode\n" +
                    "comments\n" +
                    "deliverer1_user_id\n" +
                    "deliverer1_name\n" +
                    "deliverer1_position\n" +
                    "deliverer1_cert\n" +
                    "deliverer1_id\n" +
                    "deliverer1_phone\n" +
                    "deliverer2_user_id\n" +
                    "deliverer2_name\n" +
                    "deliverer2_position\n" +
                    "deliverer2_cert\n" +
                    "deliverer2_id\n" +
                    "deliverer2_phone\n"
    )
    @SysLog("修改委托")
    @PutMapping("/submitter_save")
    @PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public R<Entrustment> bizSubmitter_Save(@RequestBody Entrustment entrust, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizSubmitter_Save(entrust, dlpUser), "保存委托信息成功");
    }

    /**
     * 更新送检员
     */


    /**
     * 委托创建者 提交委托供审核
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "提交委托供审核", notes = "提交委托供审核")
    @SysLog("提交委托供审核")
    @PutMapping("/submitter_apply")
    @PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public R bizSubmitter_Apply(@RequestBody Entrustment entrust, HttpServletRequest theHttpServletRequest) {

//		System.out.println(String.format("theHttpServletRequest.toString()=%s", theHttpServletRequest.toString()));
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizSubmitter_Apply(entrust, dlpUser), "委托提交成功");
    }


    /**
     * 审核者认领审核任务
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "审核者认领审核任务", notes = "审核者认领审核任务")
    @SysLog("审核者认领审核任务")
    @PutMapping("/checker_claim")
    @PreAuthorize("@pms.hasPermission('EntrustmentCheck')")
    public R bizChecker_Claim(@RequestBody Entrustment entrust, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizChecker_Claim(entrust, dlpUser), "委托审核任务认领成功");
    }

    /**
     * 审核者对委托进行审核
     * <p>
     * 审核者还修改以下属性:
     * destructiveAnalysis      鉴定事项确认书, 检验: 有损/无损
     * otherIdentificationNotes 鉴定事项确认书, 检验: 其他
     * otherAgreement           鉴定事项确认书, 其他约定事项: 其他
     * checkComments            审核意见: (审批通过 审批不通过及原因)
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "审核者对委托进行审核", notes = "审核者对委托进行审核" +
            "destructiveAnalysis      鉴定事项确认书, 检验: 有损/无损\n" +
            "otherIdentificationNotes 鉴定事项确认书, 检验: 其他\n" +
            "otherAgreement           鉴定事项确认书, 其他约定事项: 其他\n" +
            "avoidIdentifier          回避人及回避原因\n" +
            "comments                 备注\n" +

            "checkComments            审核意见: (审核通过/审核不通过及原因)"
    )
    @SysLog("审核者对委托进行审核")
    @PutMapping("/checker_apply")
    @PreAuthorize("@pms.hasPermission('EntrustmentCheck')")
    public R bizChecker_Apply(@RequestBody Entrustment entrust, Integer opCode, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        //让第三方系统完成审核-----------------------------------------------------------------------------结束
        return R.ok(entrustmentService.bizChecker_Apply(entrust, opCode, dlpUser), "委托审核完成");
    }


    /**
     * 审批者认领审批任务
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "审批者认领审批任务", notes = "审批者认领审批任务")
    @SysLog("审批者认领审批任务")
    @PutMapping("/approver_claim")
    @PreAuthorize("@pms.hasPermission('EntrustmentApprove')")
    public R bizApprover_Claim(@RequestBody Entrustment entrust, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        return R.ok(entrustmentService.bizApprover_Claim(entrust, dlpUser), "委托审批任务认领成功");
    }

    /**
     * 审批者对委托进行审批
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "审批者对委托进行审批", notes = "审批者对委托进行审批" +
            "destructiveAnalysis      鉴定事项确认书, 检验: 有损/无损\n" +
            "otherIdentificationNotes 鉴定事项确认书, 检验: 其他\n" +
            "otherAgreement           鉴定事项确认书, 其他约定事项: 其他\n" +
            "avoidIdentifier          回避人及回避原因\n" +
            "comments                 备注\n" +

            "approveComments          审批意见: (审批通过/审批不通过及原因)"
    )
    @SysLog("审批者对委托进行审批")
    @PutMapping("/approver_apply")
    @PreAuthorize("@pms.hasPermission('EntrustmentApprove')")
    public R bizApprover_Apply(@RequestBody Entrustment entrust, Integer opCode, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizApprover_Apply(entrust, opCode, dlpUser), "委托审批完成");
    }

    /**
     * 委托方领导确认送检
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "委托方领导确认送检", notes = "委托方领导确认送检")
    @SysLog("委托方领导确认送检")
    @PutMapping("/confirmer_apply")
    @PreAuthorize("@pms.hasPermission('EntrustmentConfirm')")
    public R bizConfirm_Apply(@RequestBody Entrustment entrust, Integer opCode, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizConfirm_Apply(entrust, opCode, dlpUser), "委托送检确认完成");
    }


    /**
     * 委托创建人送检保存
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "委托创建人送检保存", notes = "委托创建人送检保存")
    @SysLog("委托创建人送检保存")
    @PutMapping("/deliver_save")
    @PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public R bizDeliver_Save(@RequestBody Entrustment entrust, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizDeliver_Save(entrust, dlpUser), "委托送检信息保存完成");
    }

    /**
     * 委托创建人送检提交
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "委托创建人送检提交", notes = "委托创建人送检提交")
    @SysLog("委托创建人送检提交")
    @PutMapping("/deliver_apply")
    @PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public R bizDeliver_Apply(@RequestBody Entrustment entrust, Integer opCode, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizDeliver_Apply(entrust, opCode, dlpUser), "委托送检提交完成");
    }


    /**
     * 下载鉴定委托书
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "下载鉴定委托书", notes = "下载鉴定委托书。如果还没有创建, 立即创建: 根据鉴定委托书模板和委托的内容创建PDF格式的鉴定委托书, 并保存到 MinIO 存储中")
    @SysLog("创建鉴定委托书")
    @GetMapping("/el")
//	@PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public String  bizGetPDFEntrustmentLetter(String id, HttpServletRequest theHttpServletRequest, HttpServletResponse httpServletResponse) {
        return entrustmentService.bizGetPDFEntrustmentLetter(id, theHttpServletRequest, httpServletResponse);
    }

    /**
     * 受理完成
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "受理保存", notes = "在受理时保存受理员录入的数据" +
            "destructiveAnalysis      鉴定事项确认书, 检验: 有损/无损\n" +
            "otherIdentificationNotes 鉴定事项确认书, 检验: 其他\n" +
            "otherAgreement           鉴定事项确认书, 其他约定事项: 其他\n" +
            "avoidIdentifier          回避人及回避原因\n" +
            "comments                 备注\n" +

            "acceptComments          受理意见: (受理通过/受理不通过及原因)"
    )
    @SysLog("受理保存")
    @PutMapping("/accept_save")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R bizAccept_Save(@RequestBody Entrustment entrust, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizAccept_Save(entrust, dlpUser), "受理员录入的数据已保存");
    }

    /**
     * 受理完成
     * 这个是所有检材都受理完成后，才可对委托书点受理完成   ---------------
     *
     * @param entrust
     * @return
     */
    @ApiOperation(value = "受理完成", notes = "受理完成" +
            "destructiveAnalysis      鉴定事项确认书, 检验: 有损/无损\n" +
            "otherIdentificationNotes 鉴定事项确认书, 检验: 其他\n" +
            "otherAgreement           鉴定事项确认书, 其他约定事项: 其他\n" +
            "avoidIdentifier          回避人及回避原因\n" +
            "comments                 备注\n" +

            "acceptComments          受理意见: (受理通过/受理不通过及原因)"
    )
    @SysLog("受理完成")
    @PutMapping("/accept_apply")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R bizAccept_Apply(@RequestBody Entrustment entrust, Integer opCode, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        //同步第三方禁毒系统的受理功能 结束--------------------------------------------------------------
        return R.ok(entrustmentService.bizAccept_Apply(entrust, opCode, dlpUser), "委托受理结束");
    }


    /**
     * 下载鉴定事项确认书
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "下载鉴定事项确认书", notes = "下载鉴定事项确认书。如果还没有创建, 立即创建: 根据鉴定事项确认书模板和委托的内容创建PDF格式的鉴定事项确认书, 并保存到 MinIO 存储中")
    @SysLog("创建鉴定事项确认书")
    @GetMapping("/iicl")
//	@PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public void bizGetPDFIdentifyItemsConfirmLetter(String id, String pdfOrWord, HttpServletRequest theHttpServletRequest, HttpServletResponse httpServletResponse) {
        entrustmentService.bizGetPDFIdentifyItemsConfirmLetter(id, pdfOrWord, theHttpServletRequest, httpServletResponse);
    }

    /*
     * 生成鉴定事项确认书
     *
     * @return
     */
    private void GenerateIdentifyItemsConfirmLetterPDF(EntrustmentVO ev /*, HttpServletRequest theHttpServletRequest, HttpServletResponse httpServletResponse*/) {
        entrustmentService.GenerateIdentifyItemsConfirmLetterPDF(ev);
    }


    /**
     * 委托列表
     *
     * @param entrustment 委托 查询条件
     * @return
     */
    @ApiOperation(value = "委托列表", notes = "委托列表")
    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('EntrustmentList')")
    public R<List<EntrustmentVO>> getEntrustmentList(Entrustment entrustment,
                                                     @RequestParam(value = "fromDate", required = false) String fromDate,
                                                     @RequestParam(value = "toDate", required = false) String toDate,
                                                     @RequestParam(value = "entrustmentNo", required = false) String entrustmentNo,
                                                     @RequestParam(value = "caseId", required = false) String caseId,
                                                     @RequestParam(value = "caseNo", required = false) String caseNo,
                                                     @RequestParam(value = "keywords", required = false) String keywords,
                                                     @RequestParam(value = "includeOtherOne", required = false) Boolean includeOtherOne,
                                                     @RequestParam(value = "hasIdentificationId", required = false) Boolean hasIdentificationId,
                                                     @RequestParam(value = "entrustmentIds", required = false) List<String> entrustmentIds,
                                                     @RequestParam(value = "statuses", required = false) List<String> statuses
    ) {
        String orgId = null;
        DLPUser dlpUser = SecurityUtils.getUser();
        System.out.println(String.format("getEntrustmentList 用户 %s 的 id=%s [%s]", dlpUser.getUsername(), dlpUser.getId(), (dlpUser.isStaff()) ? "鉴定机构员工" : "普通用户"));

        if (dlpUser.isStaff()) {
            //-- 当前用户是鉴定中心员工, 代录数据  && dlpUser.HasPermission("EntrustmentAidInput")
            System.out.println(String.format("用户 %s 的 id=%s, 是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            List<EntrustmentVO> r = entrustmentService.getEntrustmentVOList(Wrappers.<Entrustment>query()
                            .and(StrUtil.isNotBlank(keywords), wrapper -> wrapper
                                    .like("e.entrustment_no", keywords)
                                    .or()
                                    .like("e.client_org_name", keywords)
                                    .or()
                                    .like("e.accept_no", keywords)
                                    .or()
                                    .like("c.case_name", keywords))
//                    .eq((includeOtherOne == null || !includeOtherOne), "e.create_by", dlpUser.getId())
                            .eq("e.client_org_id", dlpUser.getOrgId())
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .isNotNull(hasIdentificationId != null && hasIdentificationId, "e.identification_id")
                            .in(entrustmentIds != null && entrustmentIds.size() > 0, "e.id", entrustmentIds)
                            .eq(StrUtil.isNotBlank(entrustment.getIdentificationId()), "e.identification_id", entrustment.getIdentificationId())
                            .eq(entrustment.getStatus() != null, "e.status", entrustment.getStatus())
                            .eq(entrustment.getReturnOrNot() != null, "e.return_or_not", entrustment.getReturnOrNot())
                            .in(statuses != null && statuses.size() > 0, "e.status", statuses)

                            //.ne(((isSubmitted != null) && isSubmitted), "e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                            .orderByDesc("e.create_time")
            );
            return R.ok(r);
        } else {
            //-- 当前用户是普通用户, 不是鉴定中心员工
            System.out.println(String.format("用户 %s 的 id=%s, 不是鉴定机构员工", dlpUser.getUsername(), dlpUser.getId()));
            orgId = dlpUser.getOrgId(); // 如果不是鉴定中心员工, 则只能看员工所属机构的案件

            List<EntrustmentVO> r = entrustmentService.getEntrustmentVOList(Wrappers.<Entrustment>query()
                            .and(StrUtil.isNotBlank(keywords), wrapper -> wrapper
                                    .like("e.entrustment_no", keywords)
                                    .or()
                                    .like("e.client_org_name", keywords)
                                    .or()
                                    .like("e.accept_no", keywords)
                                    .or()
                                    .like("c.case_name", keywords))
//                    .eq((includeOtherOne == null || !includeOtherOne), "e.create_by", dlpUser.getId())
                            .eq("e.client_org_id", orgId)
                            .ge(StrUtil.isNotBlank(fromDate), "e.create_time", fromDate)
                            .le(StrUtil.isNotBlank(toDate), "e.create_time", toDate)
                            .like(StrUtil.isNotBlank(entrustmentNo), "e.entrustment_no", entrustmentNo)
                            .eq(StrUtil.isNotBlank(caseId), "e.case_id", caseId)
                            .like(StrUtil.isNotBlank(caseNo), "c.case_no", caseNo)
                            .isNotNull(hasIdentificationId != null && hasIdentificationId, "e.identification_id")
                            .eq(entrustment.getStatus() != null, "e.status", entrustment.getStatus())
                            .eq(entrustment.getReturnOrNot() != null, "e.return_or_not", entrustment.getReturnOrNot())
                            .in(statuses != null && statuses.size() > 0, "e.status", statuses)
                            //.ne(((isSubmitted != null) && isSubmitted), "e.status", EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus())
                            .orderByDesc("e.create_time")
            );
            return R.ok(r);
        }
    }

    /**
     * 新增委托
     *
     * @param entrustment 委托
     * @return R
     */
    @ApiOperation(value = "新增委托", notes = "新增委托")
    @SysLog("新增委托")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('EntrustmentCreate')")
    public R<Entrustment> bizSubmitter_AddEntrustment(@RequestBody Entrustment entrustment, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.bizSubmitter_AddEntrustment(entrustment, dlpUser));
    }

    /**
     * 新增委托(11-13修改版)
     *
     * @param entrustmentDTO 委托接受参数
     * @return R
     */
    @ApiOperation(value = "新增委托(11-13新修改)", notes = "新增委托(11-13新修改)")
    @SysLog("新增委托")
    @PostMapping("/add/new")
    @PreAuthorize("@pms.hasPermission('EntrustmentCreate')")
    public R<Entrustment> addOne(@RequestBody EntrustmentDTO entrustmentDTO, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.addNewEmt(entrustmentDTO, dlpUser));
    }

    @GetMapping("/initSendAcceptData")
    public R initSendAcceptData() {
        entrustmentService.initCaseSendAccept();
        return R.ok(true, "初始化完成");
    }

    /**
     * 修改委托 <--- 这个接口会被禁止, 因为委托不允许直接修改, 应该按不同的用户和委托的状态, 对不同的字段有适当的修改权。应该使用下面的与业务相关的接口修改委托信息
     *
     * @param entrustment 委托
     * @return R
     */
    @ApiOperation(value = "修改委托 <--- 这个接口会被禁止, 因为委托不允许直接修改, 应该按不同的用户和委托的状态, 对不同的字段有适当的修改权。应该使用下面的与业务相关的接口修改委托信息",
            notes = "修改委托 <--- 这个接口会被禁止, 因为委托不允许直接修改, 应该按不同的用户和委托的状态, 对不同的字段有适当的修改权。应该使用下面的与业务相关的接口修改委托信息")
    @SysLog("修改委托")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('EntrustmentEdit')")
    public R xxxx_putUpdateById(@RequestBody Entrustment entrustment, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        entrustment.setCreateBy(null);
        entrustment.setCreateTime(null);
        entrustment.setUpdateBy(dlpUser.getId());
        entrustment.setUpdateTime(LocalDateTime.now());

        if (entrustmentService.updateById(entrustment)) {
            return R.ok(entrustment, "保存委托信息成功");
        } else {
            return R.failed(entrustment, "保存委托信息失败");
        }
    }

    /**
     * 通过id删除委托
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除委托", notes = "通过id删除委托")
    @SysLog("通过id删除委托")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('EntrustmentDelete')")
    public R deleteById(@PathVariable String id, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return entrustmentService.deleteById(id, dlpUser);
    }


    /**
     * 取指定委托的附件列表
     *
     * @param entrustmentId
     * @return
     */
    @GetMapping("/attachment/{entrustmentId}/list")
    @PreAuthorize("@pms.hasPermission('EntrustmentAttachmentList')")
    public R getAttachmentList(@PathVariable("entrustmentId") String entrustmentId) {
        Entrustment entrustment = entrustmentService.getById(entrustmentId);
        if (entrustment != null) {
            return R.ok(ossFile.fileList(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + entrustmentId));
        }
        return R.failed("不存在这个委托");
    }

    /**
     * 取指定委托的指定附件
     *
     * @param entrustmentId
     * @param fileName
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/attachment/{entrustmentId}/{fileName}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAttachmentDownload')")
    public void getAttachmentObj(@PathVariable("entrustmentId") String entrustmentId, @PathVariable String fileName, HttpServletResponse httpServletResponse) throws Exception {
        Entrustment entrustment = entrustmentService.getById(entrustmentId);
        if (entrustment != null) {
            try {
                ossFile.fileGet(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + entrustmentId + "/" + 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/{entrustmentId}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAttachmentUpload')")
    public R uploadAttachmentObj(@PathVariable("entrustmentId") String entrustmentId, @RequestPart("file") MultipartFile file) throws Exception {
        System.out.println(String.format("uploadPhotoObj: entrustmentId=%s OriginalFilename=%s", entrustmentId, file.getOriginalFilename()));
        Entrustment entrustment = entrustmentService.getById(entrustmentId);
        if (entrustment != null) {
            String path = OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + entrustmentId;
            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("上传失败");
        }
        return R.failed("不存在这个委托");
    }

    @PostMapping(value = "/attachment_base64/{entrustmentId}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAttachmentUpload')")
    public R uploadAttachmentObj_Base64(@PathVariable("entrustmentId") String entrustmentId, @RequestBody JSONObject jsonParam) throws Exception {
        return entrustmentService.uploadAttachmentObj_Base64(entrustmentId, jsonParam);
    }


    @DeleteMapping("/attachment/{entrustmentId}/{fileName}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAttachmentDelete')")
    public R deleteAttachmentObj(@PathVariable("entrustmentId") String entrustmentId, @PathVariable String fileName) throws Exception {
        Entrustment cj = entrustmentService.getById(entrustmentId);
        if (cj != null) {
            ossFile.fileDelete(OSSDirectoryConstants.ENTRUSTMENT_DIRECTORY + "/" + entrustmentId + "/" + fileName);
            Map<String, String> ResultData = new HashMap<>();
            ResultData.put("fileName", fileName);
            return R.ok(ResultData, "删除文件成功");
        }
        return R.failed("不存在这个委托");
    }


    ///// 受理时的


    /**
     * 取指定委托的受理时的列表
     *
     * @param entrustmentId
     * @return
     */
    @GetMapping("/accept_attachment/{entrustmentId}/list")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R getAcceptAttachmentList(@PathVariable("entrustmentId") String entrustmentId) {
        Entrustment entrustment = entrustmentService.getById(entrustmentId);
        if (entrustment != null) {
            return R.ok(ossFile.fileList(OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + entrustmentId));
        }
        return R.failed("不存在这个委托");
    }

    /**
     * 取指定委托的受理时的指定附件
     *
     * @param entrustmentId
     * @param fileName
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/accept_attachment/{entrustmentId}/{fileName}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public void getAcceptAttachmentObj(@PathVariable("entrustmentId") String entrustmentId, @PathVariable String fileName, HttpServletResponse httpServletResponse) throws Exception {
        Entrustment entrustment = entrustmentService.getById(entrustmentId);
        if (entrustment != null) {
            try {
                ossFile.fileGet(OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + entrustmentId + "/" + 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, "不存在这个委托");
        }
    }

    //保存送检人的证件照片信息
    @ApiOperation(value = "上传送检人的证件照片", notes = "上传送检人的证件照片")
    @PostMapping("/delivePhotoUpload/{entrustmentId}")
    public R uploadDeliverPhoto(@PathVariable("entrustmentId") String entrustmentId, @RequestPart("file") MultipartFile file) {
        Assert.notBlank(entrustmentId, "委托ID不能为空");
        //证件照片特殊文件标识
        String deliverPhoto = "deliverPhoto";
        String path = OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + entrustmentId + "/" + deliverPhoto;
        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, "上传成功");
        } else {
            return R.failed("上传失败");
        }
    }

    @ApiOperation(value = "上传送检人的证件照片——base64方式", notes = "上传送检人的证件照片——base64方式")
    @PostMapping("/delivePhotoUpload_base64/{entrustmentId}")
    public R uploadDeliverPhoto_Base64(@PathVariable("entrustmentId") String entrustmentId, @RequestBody JSONObject jsonParam) {
        return entrustmentService.uploadDeliverPhoto_Base64(entrustmentId, jsonParam);
    }

    //获取送检人合并后的照片
//    @ApiOperation(value = "获取送检人合并后的照片", notes = "获取送检人合并后的照片")
//    @GetMapping("/getDeliverMergePhoto")
//    public R getDeliverMergePhoto(String entrustId, HttpServletRequest request, HttpServletResponse response) {
//        //复杂一点的业务我们放到service中去处理
//        String fileFullPath = OSSDirectoryConstants.DOCUMENT_ACCEPT_DIRECTORY + "/" + entrustId + "/" + OSSDirectoryConstants.DOCUMENT_ACCEPT_DIRECTORY_DELIVER + "/alldeliverpic.docx";
//        try {
//            if (ossFile.objectExist(fileFullPath)) {
//                ossFile.fileGet(fileFullPath, response.getOutputStream());
//            } else {
//                boolean ret = entrustmentService.getDeliverMergePhoto(entrustId);
//                if (ret) {
//                    ossFile.fileGet(fileFullPath, response.getOutputStream());
//                }
//            }
//        } catch (Exception err) {
//            return R.failed("");
//        }
//        return R.ok(true, "获取文件成功");
//    }

    @ApiOperation(value = "获取送检人合并后的照片URL", notes = "获取送检人合并后的照片URL")
    @GetMapping("/getDeliverMergePhotoUrl")
    public R getDeliverMergePhotoUrl(String entrustId, HttpServletRequest request, HttpServletResponse response) {
        Entrustment entrustment = entrustmentService.getById(entrustId);
        String acceptNo = entrustment.getAcceptNo();
        CaseEvent caseEvent = caseEventService.getById(entrustment.getCaseId());
        String caseName = caseEvent.getCaseName();
        String deliverer1Name = entrustment.getDeliverer1Name();
        String deliverer2Name = entrustment.getDeliverer2Name();
        //复杂一点的业务我们放到service中去处理
        String fileFullPath = OSSDirectoryConstants.DOCUMENT_ACCEPT_DIRECTORY + "/" + entrustId + "/" + OSSDirectoryConstants.DOCUMENT_ACCEPT_DIRECTORY_DELIVER + "/alldeliverpic.docx";
        try {
            if (ossFile.objectExist(fileFullPath)) {
                //ossFile.fileGet(fileFullPath,response.getOutputStream());
            } else {
                boolean ret = entrustmentService.getDeliverMergePhoto(entrustId, acceptNo, caseName, deliverer1Name, deliverer2Name);
                if (ret) {
                    //ossFile.fileGet(fileFullPath,response.getOutputStream());
                }
            }
        } catch (Exception err) {
            return R.failed("获取文件失败");
        }
        String uuid = IdWorker.get32UUID();
        return R.ok(uuid + "#" + fileFullPath, "获取文件成功");
    }
    //由于远程调用feign接口效率的原因，现在获取检材照片已经不需要通过受理系统处理，直接调用word2pdf服务接口即可
//    @ApiOperation(value = "获取检材合并照片", notes = "获取检材合并照片")
//    @GetMapping("/getMaterialPhoto")
//    public R getMaterialPhoto(String entrustId, HttpServletRequest request, HttpServletResponse response, Integer groupCount) {
//        //复杂一点的业务我们放到service中去处理
//        String fileFullPath = OSSDirectoryConstants.DOCUMENT_ACCEPT_DIRECTORY + "/" + entrustId + "/materialPhoto/materialallpic.docx";
//        try {
////            if (ossFile.objectExist(fileFullPath)) {
////                ossFile.fileGet(fileFullPath, response.getOutputStream());
////            } else {
////                boolean ret = entrustmentService.getMaterialMergePhoto(entrustId, groupCount);
////                if (ret) {
////                    ossFile.fileGet(fileFullPath, response.getOutputStream());
////                }
////            }
//        } catch (Exception err) {
//            return R.failed("获取文件失败");
//        }
//        return R.ok(true, "获取文件成功");
//    }
//
//    @ApiOperation(value = "获取检材合并照片url", notes = "获取检材合并照片url")
//    @GetMapping("/getMaterialPhotoUrl")
//    public R getMaterialPhotoUrl(String entrustId, HttpServletRequest request, HttpServletResponse response, Integer groupCount) {
//        //复杂一点的业务我们放到service中去处理
//        String fileFullPath = OSSDirectoryConstants.DOCUMENT_ACCEPT_DIRECTORY + "/" + entrustId + "/materialPhoto/materialallpic.docx";
//        String keyID = IdWorker.get32UUID();
//        try {
////            if (ossFile.objectExist(fileFullPath)) {
////                //ossFile.fileGet(fileFullPath,response.getOutputStream());
////            } else {
////                boolean ret = entrustmentService.getMaterialMergePhoto(entrustId,groupCount);
////                if (ret) {
////                    //ossFile.fileGet(fileFullPath,response.getOutputStream());
////                }
//////            }
//        } catch (Exception err) {
//            err.printStackTrace();
//            return R.failed("获取文件失败");
//        }
//        String uuid = IdWorker.get32UUID();
//        return R.ok(uuid + "#" + fileFullPath, "获取文件成功");
//    }


    @PostMapping(value = "/accept_attachment/{entrustmentId}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R uploadAcceptAttachmentObj(@PathVariable("entrustmentId") String entrustmentId, @RequestPart("file") MultipartFile file) throws Exception {
        System.out.println(String.format("uploadPhotoObj: entrustmentId=%s OriginalFilename=%s", entrustmentId, file.getOriginalFilename()));
        Entrustment entrustment = entrustmentService.getById(entrustmentId);
        if (entrustment != null) {
            String path = OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + entrustmentId;
            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("上传失败");
        }
        return R.failed("不存在这个委托");
    }

    /**
     * 上传委托的受理照片
     *
     * @param entrustmentId 委托Id
     * @param jsonParam     照片的 json 格式的数据。json 对象, 属性 Image 的值是 base64 格式的图像数据；属性 FileName 是文件名, 如果为空则系统自动按当前时间生成文件名
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "上传委托的受理照片", notes = "上传委托的受理照片\n" +
            "本接口需要 2 个参数。entrustmentId 是委托标识，在请求的 url 中提供; jsonParam 是 json 格式的照片数据, 在请求 body 中提供。\n" +
            "jsonParam 是一个 json 对象，有 2 个字符串类型的属性: fileName 和 image。\n" +
            "fileName 属性可以为 null，或不提供。如果 fileName 为 null 或不存在, 则系统自动生成 yyyyMMddHHmmss 格式的文件名,后缀自动根据图像格式识别。\n" +
            "image 属性是 base64 格式的图像数据, 大致是以 \"data:image/jpeg;base64,...\" 这样的字符串开始"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "entrustmentId", value = "委托Id", required = true, paramType = "path"),
            @ApiImplicitParam(name = "jsonParam", value = "照片的 json 格式的数据", required = true, paramType = "body"),
    })
    @PostMapping(value = "/accept_attachment_base64/{entrustmentId}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R uploadAcceptAttachmentObj_Base64(@PathVariable("entrustmentId") String entrustmentId, @RequestBody JSONObject jsonParam) throws Exception {
        return entrustmentService.uploadAcceptAttachmentObj_Base64(entrustmentId, jsonParam);
    }


    @DeleteMapping("/accept_attachment/{entrustmentId}/{fileName}")
    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    public R deleteAcceptAttachmentObj(@PathVariable("entrustmentId") String entrustmentId, @PathVariable String fileName) throws Exception {
        Entrustment cj = entrustmentService.getById(entrustmentId);
        if (cj != null) {
            ossFile.fileDelete(OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + entrustmentId + "/" + fileName);
            Map<String, String> ResultData = new HashMap<>();
            ResultData.put("fileName", fileName);
            return R.ok(ResultData, "删除文件成功");
        }
        return R.failed("不存在这个委托");
    }


    //=====================================================================================
    // 涉及流程的操作
    //=====================================================================================


    /**
     * 取指定环节可用的用户列表
     * 当流程进行到某个环节的时候, 需要某个用户对这个环节进行处理(通过或不通过)。
     * 这里取可用的用户列表
     * <p>
     * 涉及到的环境有以下几个:
     * 1、创建委托及提交
     * 委托的提交者就是委托的创建者。不存在不通过的可能。
     * 2、审核
     * 审核者有几个条件: (1)必须是鉴定中心的工作人员 (2)必须拥有委托审核权限
     * 3、审批
     * 审核者有几个条件: (1)必须是鉴定中心的工作人员 (2)必须拥有委托审批权限
     * 4、送检确认
     * 送检确认者有几个条件: (1)必须与委托的创建者是同一个机构, 或上级机构的人 (2)必须拥有委托送检确认权限
     * 5、受理
     * 受理者有几个条件: (1)必须是鉴定中心的工作人员 (2)必须拥有委托受理权限
     *
     * @return
     */
    @ApiOperation(value = "取下一环节可用的用户列表", notes = "取下一环节可用的用户列表")
    @GetMapping("/available_user_list/{entrustmentId}")
    //@PreAuthorize("@pms.hasPermission('entrustment_entrustment_get')" )
    public R<List<SysUser>> bizGetAvailableUserList(@PathVariable("entrustmentId") String entrustmentId) {
        return entrustmentService.bizGetAvailableUserList(entrustmentId);
    }


    //同步第三方系统而调用的方法
    //审核委托

    /**
     * 审核审批第三方委托
     *
     * @param userFlag  用户标识
     * @param entrustId 我方委托ID，通过这个ID 查出对方的委托ID
     * @param dataPath
     * @param result
     * @param reMark
     */

    /**
     * 根据委托书ID获取相应的文书
     *
     * @param entrustId
     * @param whatBook
     * @return
     */
    @GetMapping("/getBookNameByEntrustId")
    public R getBookNameByEntrustId(String entrustId, String whatBook) {
        String fileOssPath = entrustmentService.getBookNameByEntrustId(entrustId, whatBook);
        Assert.notBlank(fileOssPath, "获取文书失败，请检查参数");
        String docId = IdWorker.get32UUID();
        String dataInfo = docId + "#" + fileOssPath;
        return R.ok(dataInfo, "获取数据成功");
    }

    /**
     * 检验完成
     *
     * @param entrustID
     * @return
     */
    @PostMapping("/testsFinish")
    @ApiOperation(value = "检验完成，检验结束时调用此接口", notes = "检验完成，检验结束时调用此接口")
    public R testsFinish(@RequestParam("entrustmentId") String entrustID) {
        Assert.notBlank(entrustID, "参数错误，参数entrustID不能为空");
        return R.ok(entrustmentService.testsFinish(entrustID));
    }

    @GetMapping("/getEntrustStatusCount")
    @ApiOperation(value = "查询委托各个状态的数量", notes = "查询委托各个状态的数量")
    public R getEntrustStatusCount(@RequestParam(value = "entrustStatus") List<Integer> entrustStatus) {
        DLPUser dlpUser = SecurityUtils.getUser();
        Assert.notEmpty(entrustStatus, "参数错误，参数entrustStatus不能为空");
        return R.ok(entrustmentService.getEntrustStatusCount(entrustStatus, dlpUser));
    }

    //查询是否提供了证件照
    //查询是否提供了证件照
    @GetMapping("/checkDeliverPhoto")
    @ApiOperation(value = "检查是否已经上传了送检人证件照片", notes = "检查是否已经上传了送检人证件照片")
    public R checkDeliverPhoto(String entrustId) {
        Assert.notBlank(entrustId, "参数委托ID不能为空");
        return R.ok(entrustmentService.checkDeliverPhoto(entrustId));
    }

    //将历史数据流入到流转系统
    @PostMapping("/historyDataToTransSys")
    public R historyDataToTransSys(CommonIdDto commonIdDto) {
        System.out.println("参数entrustIds：" + commonIdDto.getIdList());
        return R.ok(entrustmentService.historyDataToTransSys("9", commonIdDto.getIdList()));
    }

    //获取待流转的数据
    @GetMapping("/needTransEntrustList")
    public R needTransEntrustList(String searchType, String searchKey) {
        List<EntrustmentVO> transEntrustList = new ArrayList<>();
        if (StringUtils.isNotBlank(searchType) && StringUtils.isNotBlank(searchKey)) {
            if (searchType.equals("1")) {
                transEntrustList = entrustmentService.getEntrustmentVOList(Wrappers.<Entrustment>query()
                        .eq("e.status", 9)
                        .eq("e.is_trans", 0)
                        .like("e.accept_no", searchKey)
                        .orderByDesc("e.accept_no"));
            }
            if (searchType.equals("2")) {
                transEntrustList = entrustmentService.getEntrustmentVOList(Wrappers.<Entrustment>query()
                        .eq("e.status", 9)
                        .eq("e.is_trans", 0)
                        .like("c.case_name", searchKey)
                        .orderByDesc("e.accept_no"));
            }
        } else {
            transEntrustList = entrustmentService.getEntrustmentVOList(Wrappers.<Entrustment>query()
                    .eq("e.status", 9)
                    .eq("e.is_trans", 0)
                    .orderByDesc("e.accept_no"));
        }
        return R.ok(transEntrustList, "获取数据成功");
    }

    //由于之前导入的数据存在缺失，所以添加一个接口，用于将之前缺失的字段补充进去
    @GetMapping("/updateImportDataInfo")
    public R updateImportData(String excuteType) {
        Assert.notBlank(excuteType, "参数excuteType不能为空");
        return R.ok(entrustmentService.updateImportData(excuteType));
    }

    //=====================================================================================
    // 测试, 为现有的案件创建一些委托
    @GetMapping("/create100")
    public R xxx_TestCreate100() {
        List<CaseEventVO> cjs = caseEventService.getCaseVoList(null, null, null, null);
        for (CaseEvent cj : cjs) {
            int num = RandomUtil.randomInt(1, 4);
            for (int i = 0; i < num; i++) {
                List<Entrustment> ces = entrustmentService.list(Wrappers.<Entrustment>query()
                        .eq("case_id", cj.getId()));

                if (ces.size() >= num) {
                    break;
                }
                Entrustment entrustment = new Entrustment();

                entrustment.setCaseId(cj.getId());
                //entrustment.setEntrustmentNo(entrustmentService.getNewEntrustmentNo(cj.getCaseNo()));
                entrustment.setEntrustmentNo(entrustmentService.getNewEntrustmentNo());
                //entrustment.setEntrustmentTime(LocalDateTime.now());
                entrustment.setClientOrgId("");
                //entrustment.setClientOrgName("");
                entrustment.setDeliverer1Name("李宏亮");
                entrustment.setDeliverer1Phone("13985001001");
                entrustment.setDeliverer1Id("522122199504042035");
                entrustment.setDeliverer2Name("西门吹雪");
                entrustment.setDeliverer2Phone("13985001002");
                entrustment.setDeliverer2Id("522122190504042031");

                //entrustment.setIdentificationOrgName("国家毒品实验室陕西分中心");    // 鉴定机构名称
                entrustment.setIdentificationDomain("毒品检验");    // 鉴定专业
                entrustment.setQualitativeAnalysis(true);       // 定性分析
                entrustment.setQuantitativeAnalysis(true);      // 定量分析
                entrustment.setOtherIdentificationRequests("无");    // 鉴定要求
                entrustment.setId(IdWorker.get32UUID().toUpperCase());

                if (entrustmentService.save(entrustment)) {
                    System.out.println("新增委托成功");
                } else {
                    System.out.println("新增委托失败");
                }

            }
        }
        return R.ok("已经为每个案件创建了 一些 委托");
    }

    @GetMapping("/get/quantity/for/Inspection")
    @ApiOperation(value = "送检系统统计当前用户(机构)送检且已受理的所有检材数量", notes = "送检系统统计当前用户(机构)送检且已受理的所有检材数量")
    public R<List<MarkersVO>> getQuantityForInspection(HttpServletRequest httpServletRequest) {
        Principal principal = httpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.getImQuantityForInspection(dlpUser));
    }

    @GetMapping("/get/inspect/makers")
    @ApiOperation(value = "送检系统统计各模块委托/任务不同状态的数量", notes = "送检系统统计各模块委托/任务不同状态的数量")
    public R<List<MarkersVO>> getInspectMarkers(HttpServletRequest httpServletRequest) {
        Principal principal = httpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.getInspectMarkers(dlpUser));
    }

    @GetMapping("/get/quantity/accept")
//    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    @ApiOperation(value = "受理系统统计已受理检材数量", notes = "受理系统统计已受理检材数量")
    public R<List<MarkersVO>> getImQuantityForAccept() {
        return R.ok(entrustmentService.getImQuantityForAccept());
    }

    @GetMapping("/accept/ent/makers")
//    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    @ApiOperation(value = "受理系统有关委托小红点标记", notes = "受理系统有关委托小红点标记")
    public R<List<MarkersVO>> getAcceptMarkers(HttpServletRequest httpServletRequest) {
        return R.ok(entrustmentService.getMarkersForEntrustment());
    }

    @GetMapping("/accept/oth/makers")
//    @PreAuthorize("@pms.hasPermission('EntrustmentAccept')")
    @ApiOperation(value = "受理系统其他小红点标记", notes = "受理系统其他小红点标记")
    public R<List<MarkersVO>> getMarkersForOther(HttpServletRequest httpServletRequest) {
        Principal principal = httpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
        return R.ok(entrustmentService.getMarkersForOther(dlpUser));
    }

    @GetMapping("/delivePhotoName_base64")
    @ApiOperation(value = "获取受理时打印的送检人图片文件名列表", notes = "获取受理时打印的送检人图片文件名列表")
    public List<String> getDeliverPhotoName(String id) {
        String path = OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + id + "/" + "deliverPhoto";
        return ossFile.fileList(path);
    }

    @GetMapping("/delivePhotoDownload_base64/{id}/{fileName}")
    @ApiOperation(value = "获取受理时打印的单个送检人图片", notes = "获取受理时打印的单个送检人图片")
    public R getDeliverPhoto(@PathVariable(value = "id") String id, @PathVariable(value = "fileName") String fileName, HttpServletResponse httpServletResponse) throws Exception {
        String path = OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + id + "/" + "deliverPhoto/" + fileName;
        Entrustment entrustment = entrustmentService.getById(id);
        if (entrustment == null) {
            throw new RuntimeException(String.format("没有找到ID为%s的委托", id));
        }
        ossFile.fileGet(path, httpServletResponse.getOutputStream());
        return R.ok("预览成功");
    }

    @DeleteMapping("del_delivePhoto_base64")
    @ApiOperation(value = "删除送检人照片", notes = "删除送检人照片")
    public R delDeliverPhoto( String id,String fileName) throws Exception {
        String path = OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + id + "/" + "deliverPhoto/" + fileName;
        ossFile.fileDelete(path);
        return R.ok("删除成功!");
    }

    @DeleteMapping("/delivePhotoDel_base64/{id}/{fileName}")
    @ApiOperation(value = "删除受理时打印的单个送检人图片", notes = "删除受理时打印的单个送检人图片")
    public R delDeliverPhoto(@PathVariable(value = "id") String id, @PathVariable String fileName, HttpServletResponse httpServletResponse) throws Exception {
        Entrustment entrustment = entrustmentService.getById(id);
        if (entrustment == null) {
            throw new RuntimeException(String.format("没有找到ID为%s的委托", id));
        }
        String path = OSSDirectoryConstants.ACCEPT_DIRECTORY + "/" + id + "/" + "deliverPhoto/" + fileName;
        ossFile.fileDelete(path);

        return R.ok("删除成功");
    }

    @PostMapping("/printSampleFile")
    @ApiOperation(value = "打印检材档案", notes = "打印检材档案")
    public void printSampleFile(String entrustmentId, HttpServletResponse httpServletResponse) throws Exception {
        String applyFileName = "检材样本档案";
        String path = "document" + "/" + "entrustmentIdentificationMaterial" + "/" + applyFileName + ".docx";
        entrustmentService.printSampleFile(entrustmentId);
        ossFile.fileGet(path, httpServletResponse.getOutputStream());
    }

    @PutMapping("/synchronization/materialType")
    @ApiOperation(value = "同步大数据平台的检材类别", notes = "同步大数据平台的检材类别")
    public R synchronizationByMaterialType() {
        return entrustmentService.synchronizationByMaterialType() ? R.ok("同步成功!") : R.failed("同步失败!");
    }

    @GetMapping("/entrustmentAndMaterial")
    @ApiOperation(value = "分页查询委托列表以及委托下的检材", notes = "分页查询委托列表以及委托下的检材")
    public R getEntrustmentAndMaterial(Page page, Integer status, String keywords) {
        return R.ok(entrustmentService.getEntrustmentAndMaterial(page, status, keywords), "数据获取成功!");
    }

    @GetMapping("/isMaterialPhoto")
    @ApiOperation(value = "查看是否已经生成好了检材照片，如果已经生成好了，则返回检材照片的路径，反之返回一个null，然后再调用生成照片的接口即可")
    public R isMaterialPhoto(String entrustmentId) {
        String path = "document/accept" + "/" + entrustmentId + "/materialPhoto/materialallpic.docx";
        return entrustmentService.isMaterialPhoto(entrustmentId) ? R.ok(path) : R.ok(null);
    }


    @PutMapping("/editRequirement")
    @ApiOperation(value = "修改鉴定要求")
    public R editRequirement(@RequestBody Entrustment entrustment){
        Entrustment entst = entrustmentService.getById(entrustment.getId());
        entst.setEntrustRequirement(entrustment.getEntrustRequirement());
        return entrustmentService.updateById(entst) ? R.ok("修改成功") : R.failed("修改失败");
    }
}
