package com.fs.company.controller.store;

import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ParseUtils;
import com.fs.framework.security.LoginUser;
import com.fs.his.domain.FsExportTask;
import com.fs.his.domain.FsInquiryDisease;
import com.fs.his.domain.FsInquiryOrderReport;
import com.fs.his.param.FsIllnessLibraryNameParam;
import com.fs.his.param.FsInquiryOrderReportParam;
import com.fs.his.service.*;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsInquiryDiseaseVO;
import com.fs.his.vo.FsInquiryOrderReportListVO;
import com.fs.his.vo.FsInquiryOrderReportVO;
import com.fs.his.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

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

/**
 * 问诊报告Controller
 *
 * @author fs
 * @date 2023-09-04
 */
@RestController
@RequestMapping("/store/inquiryOrderReport")
public class FsInquiryOrderReportController extends BaseController
{
    @Autowired
    private IFsInquiryOrderReportService fsInquiryOrderReportService;
    @Autowired
    IFsInquiryDiseaseService fsInquiryDiseaseService;
    @Autowired
    IFsIllnessLibraryService fsIllnessLibraryService;
    @Autowired
    private IFsExportTaskService exportTaskService;
    @Autowired
    IFsDoctorService fsDoctorService;
    /**
     * 查询问诊报告列表
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrderReport:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsInquiryOrderReportParam fsInquiryOrderReport)
    {
        startPage();
        LoginUser loginUser = com.fs.framework.security.SecurityUtils.getLoginUser();
        fsInquiryOrderReport.setCompanyId(loginUser.getCompany().getCompanyId());
        List<FsInquiryOrderReportListVO> list = fsInquiryOrderReportService.selectFsInquiryOrderReportListVO(fsInquiryOrderReport);
        return getDataTable(list);
    }

    /**
     * 导出问诊报告列表
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrderReport:export')")
    @Log(title = "问诊报告", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsInquiryOrderReportParam fsInquiryOrderReport)
    {

        LoginUser loginUser = com.fs.framework.security.SecurityUtils.getLoginUser();
        fsInquiryOrderReport.setCompanyId(loginUser.getCompany().getCompanyId());
        Long userId = loginUser.getUser().getUserId();
        logger.info("导出问诊报告:"+ userId);
        Integer exportType1 = exportTaskService.isExportType2(userId);
        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(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrderReport.setTaskId(task.getTaskId());
        fsInquiryOrderReportService.exportData(fsInquiryOrderReport);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }

    /**
     * 获取问诊报告详细信息
     */
    @GetMapping(value = "/{reportId}")
    public AjaxResult getInfo(@PathVariable("reportId") Long reportId)
    {
        FsInquiryOrderReportVO fsInquiryOrderReportVO = fsInquiryOrderReportService.selectFsInquiryOrderReportByReportIdVO(reportId);
        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){
                if (mobile.length()>11){
                    parse.put("mobile", PhoneUtil.decryptPhoneMk(mobile));
                }else {
                    parse.put("mobile",mobile.replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }

            }
            String s = JSON.toJSONString(parse);
            fsInquiryOrderReportVO.setPatientJson(s);
        }
        if (fsInquiryOrderReportVO.getPhone()!=null){
            if (fsInquiryOrderReportVO.getPhone().length()>11){
                fsInquiryOrderReportVO.setPhone(PhoneUtil.decryptPhoneMk(fsInquiryOrderReportVO.getPhone()));
            }else {
                fsInquiryOrderReportVO.setPhone(fsInquiryOrderReportVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }

        }
        return AjaxResult.success(fsInquiryOrderReportVO);
    }

    @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){
                if (mobile.length()>11){
                    parse.put("mobile",PhoneUtil.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);
    }

    @GetMapping(value = "/getReportId/{id}")
    public AjaxResult getReportId(@PathVariable("id") Long id)
    {
        return AjaxResult.success(fsInquiryOrderReportService.selectFsInquiryOrderReportIdByOrderId(id));
    }
    /**
     * 新增问诊报告
     */
    @PreAuthorize("@ss.hasPermi('store: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('store:inquiryOrderReport:edit')or @ss.hasPermi('his:inquiryOrderReport:audit')")
    @Log(title = "问诊报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {
        return toAjax(fsInquiryOrderReportService.updateFsInquiryOrderReport(fsInquiryOrderReport));
    }

    /**
     * 处理问诊报告
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrderReport:audit')")
    @Log(title = "问诊报告处理", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {
        LoginUser loginUser = com.fs.framework.security.SecurityUtils.getLoginUser();
        fsInquiryOrderReport.setTriageUserId(loginUser.getUser().getUserId());
        return toAjax(fsInquiryOrderReportService.updateFsInquiryOrderReportAudit(fsInquiryOrderReport));
    }

    /**
     * 处理问诊报告
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrderReport:audit')")
    @Log(title = "问诊报告处理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateAuditReport")
    public String updateAuditReport(@RequestBody FsInquiryOrderReport fsInquiryOrderReport)
    {

        LoginUser loginUser = com.fs.framework.security.SecurityUtils.getLoginUser();
       Long userId= loginUser.getUser().getUserId();

        FsInquiryOrderReport o = fsInquiryOrderReportService.selectFsInquiryOrderReportByReportId(fsInquiryOrderReport.getReportId());

        if (o.getAuditUserId()!=null||o.getTriageUserId()!=null){
            if (o.getAuditUserId()!=null){
                return "0";
            }
            if (o.getTriageUserId()!=null){
                if (o.getTriageUserId()-userId==0){
                    return "继续处理";
                }else {
                    return "0";
                }
            }
        }
        o.setTriageUserId(userId);
        fsInquiryOrderReportService.updateFsInquiryOrderReport(o);
        return "开始处理";
    }

    @GetMapping("/listBySearch")
    public TableDataInfo listBySearch(FsInquiryDisease fsInquiryDisease)
    {
        startPage();
        List<FsInquiryDiseaseVO> list = fsInquiryDiseaseService.selectFsInquiryDiseaseListVO(fsInquiryDisease);
        return getDataTable(list);
    }
    @GetMapping("/docList")
    public TableDataInfo userDoctorList()
    {
        LoginUser loginUser = com.fs.framework.security.SecurityUtils.getLoginUser();
        Long companyId = loginUser.getCompany().getCompanyId();
        List<UserVo> list = fsDoctorService.selectUserDocVoListByCompany(companyId);
        return getDataTable(list);
    }
    @GetMapping(value = "getIllness")
    public TableDataInfo getIllness(FsIllnessLibraryNameParam name)
    {

        startPage();
        return getDataTable(fsIllnessLibraryService.selectFsIllnessLibraryVOByIllnessName(name.getName()));
    }

    @Log(title = "问诊报告电话", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store: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("患者信息为空") ;
    }


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