package com.fs.his.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.his.domain.FsExportTask;
import com.fs.his.domain.FsInquiryDisease;
import com.fs.his.param.FsInquiryOrderReportParam;
import com.fs.his.service.IFsExportTaskService;
import com.fs.his.service.IFsInquiryDiseaseService;
import com.fs.his.vo.FsInquiryDiseaseVO;
import com.fs.his.vo.FsInquiryOrderReportListVO;
import com.fs.his.vo.FsInquiryOrderReportVO;
import com.qiniu.util.Json;
import com.sun.media.jfxmedia.logging.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.his.domain.FsInquiryOrderReport;
import com.fs.his.service.IFsInquiryOrderReportService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

import static com.fs.his.utils.PhoneUtil.*;

/**
 * 问诊报告Controller
 *
 * @author fs
 * @date 2023-09-04
 */
@RestController
@RequestMapping("/his/inquiryOrderReport")
public class FsInquiryOrderReportController extends BaseController
{
    @Autowired
    private IFsInquiryOrderReportService fsInquiryOrderReportService;
    org.slf4j.Logger logger= LoggerFactory.getLogger(getClass());

    /**
     * 查询问诊报告列表
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsInquiryOrderReportParam fsInquiryOrderReport)
    {
        startPage();
        if (getUserId().equals(54L)||getUserId().equals(211L)){
            fsInquiryOrderReport.setCompanyId(188L);
        }
        List<FsInquiryOrderReportListVO> list = fsInquiryOrderReportService.selectFsInquiryOrderReportListVO(fsInquiryOrderReport);
        for (FsInquiryOrderReportListVO vo : list){
            if (vo.getPhone()!=null){
                vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
        }
        return getDataTable(list);
    }
    @Autowired
    private IFsExportTaskService exportTaskService;


    /**
     * 导出问诊报告列表
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:export')")
    @Log(title = "咨询报告", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsInquiryOrderReportParam fsInquiryOrderReport)
    {
        logger.info("tc>\n【咨询报告】：{}", SecurityUtils.getUserId());
        if (fsInquiryOrderReportService.isEntityNull(fsInquiryOrderReport)){
            return AjaxResult.error("请筛选数据导出");
        }
        if (getUserId().equals(54L)||getUserId().equals(211L)){
            fsInquiryOrderReport.setCompanyId(188L);
        }
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        Long count = fsInquiryOrderReportService.selectFsInquiryOrderReportListVOCount(fsInquiryOrderReport);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(9);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("咨询报告导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrderReport.setTaskId(task.getTaskId());
        fsInquiryOrderReportService.exportData(fsInquiryOrderReport);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }

    /**
     * 获取问诊报告详细信息
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:query')")
    @GetMapping(value = "/{reportId}")
    public AjaxResult getInfo(@PathVariable("reportId") Long reportId)
    {
        FsInquiryOrderReportVO fsInquiryOrderReportVO = fsInquiryOrderReportService.selectFsInquiryOrderReportByReportIdVO(reportId);
        if (fsInquiryOrderReportVO.getPhone()!=null){
            fsInquiryOrderReportVO.setPhone(ParseUtils.parsePhone(fsInquiryOrderReportVO.getPhone()));
        }
        String patientJson = fsInquiryOrderReportVO.getPatientJson();
        if (patientJson!=null&&patientJson!=""){
            Map<String,String> parse = (Map<String,String>)JSON.parse(patientJson);
            String idCard = parse.get("idCard");
            if (idCard!=null){
                parse.put("idCard",idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1**********$2"));
            }
            String mobile = parse.get("mobile");

            if (mobile!=null&&mobile.length()>11){
                parse.put("mobile",decryptPhoneMk(mobile));
            }else {
                parse.put("mobile",mobile.replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            String s = JSON.toJSONString(parse);
            fsInquiryOrderReportVO.setPatientJson(s);
        }
        return AjaxResult.success(fsInquiryOrderReportVO);
    }

    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:query')")
    @GetMapping(value = "/orderId/{orderId}")
    public AjaxResult getCodeInfo(@PathVariable("orderId") Long orderId)
    {
        FsInquiryOrderReportVO fsInquiryOrderReportVO = fsInquiryOrderReportService.selectFsInquiryOrderReportByOrderIdVO(orderId);
        if (fsInquiryOrderReportVO.getPhone()!=null){
            fsInquiryOrderReportVO.setPhone(ParseUtils.parsePhone(fsInquiryOrderReportVO.getPhone()));
        }
        String patientJson = fsInquiryOrderReportVO.getPatientJson();
        if (patientJson!=null&&patientJson!=""){
            Map<String,String> parse = (Map<String,String>)JSON.parse(patientJson);
            String idCard = parse.get("idCard");
            if (idCard!=null){
                parse.put("idCard",idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1**********$2"));
            }
            String mobile = parse.get("mobile");
            if (mobile!=null&&mobile.length()>11){
                parse.put("mobile",decryptPhoneMk(mobile));
            }else {
                parse.put("mobile",mobile.replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            String s = JSON.toJSONString(parse);
            fsInquiryOrderReportVO.setPatientJson(s);
        }
        return AjaxResult.success(fsInquiryOrderReportVO);
    }
    @Log(title = "问诊报告电话", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:queryPatientMobile')")
    @GetMapping(value = "/queryPatientMobile/{reportId}")
    public R getPatientMobile(@PathVariable("reportId") Long reportId)
    {

        FsInquiryOrderReportVO fsInquiryOrderReportVO = fsInquiryOrderReportService.selectFsInquiryOrderReportByReportIdVO(reportId);
        String patientJson = fsInquiryOrderReportVO.getPatientJson();
        if (patientJson!=null&&!patientJson.equals("")){
            Map<String,String> parse = (Map<String,String>)JSON.parse(patientJson);
            String mobile = parse.get("mobile");
            if (mobile!=null&&mobile.length()>11){
                mobile=decryptPhone(mobile);
            }
            return R.ok().put("mobile",mobile);
        }

       return R.error("患者信息为空") ;
    }
    @GetMapping(value = "/getReportId/{id}")
    public AjaxResult getReportId(@PathVariable("id") Long id)
    {
        return AjaxResult.success(fsInquiryOrderReportService.selectFsInquiryOrderReportIdByOrderId(id));
    }
    /**
     * 新增问诊报告
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:add')")
    @Log(title = "问诊报告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {
        return toAjax(fsInquiryOrderReportService.insertFsInquiryOrderReport(fsInquiryOrderReport));
    }



    @GetMapping("/getBody")
    public String getBody()
    {
        return fsInquiryOrderReportService.selectFsTestBody();
    }


    /**
     * 修改问诊报告
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:edit')or @ss.hasPermi('his:inquiryOrderReport:audit')")
    @Log(title = "问诊报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {
        FsInquiryOrderReportVO fsInquiryOrderReportVO = fsInquiryOrderReportService.selectFsInquiryOrderReportByReportIdVO(fsInquiryOrderReport.getReportId());
        fsInquiryOrderReport.setPatientJson(fsInquiryOrderReportVO.getPatientJson());
        return toAjax(fsInquiryOrderReportService.updateFsInquiryOrderReport(fsInquiryOrderReport));
    }

    /**
     * 处理问诊报告
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:audit')")
    @Log(title = "问诊报告处理", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {
        fsInquiryOrderReport.setAuditUserId(SecurityUtils.getUserId());
        return toAjax(fsInquiryOrderReportService.updateFsInquiryOrderReportAudit(fsInquiryOrderReport));
    }

    /**
     * 处理问诊报告
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:audit')")
    @Log(title = "问诊报告处理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateAuditReport")
    public String updateAuditReport(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {
        Long userId = SecurityUtils.getUserId();
        FsInquiryOrderReport o = fsInquiryOrderReportService.selectFsInquiryOrderReportByReportId(fsInquiryOrderReport.getReportId());
        if (o.getAuditUserId()!=null||o.getTriageUserId()!=null){
            if (o.getTriageUserId()!=null){
                return "0";
            }
            if (o.getAuditUserId()!=null){
                if (o.getAuditUserId()-userId==0){
                    return "继续处理";
                }else {
                    return "0";
                }
            }
        }

        o.setAuditUserId(userId);
        o.setUpdateTime(DateUtils.getNowDate());
        fsInquiryOrderReportService.updateFsInquiryOrderReport(o);

        return "开始处理";
    }


    /**
     * 删除问诊报告
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrderReport:remove')")
    @Log(title = "问诊报告", businessType = BusinessType.DELETE)
	@DeleteMapping("/{reportIds}")
    public AjaxResult remove(@PathVariable Long[] reportIds)
    {
        return toAjax(fsInquiryOrderReportService.deleteFsInquiryOrderReportByReportIds(reportIds));
    }
}
