package com.fs.his.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.utils.SecurityUtils;
import com.fs.his.domain.FsExportTask;
import com.fs.his.domain.FsPatient;
import com.fs.his.mapper.FsPatientMapper;
import com.fs.his.param.FsPrescribeParam;
import com.fs.his.service.IFsExportTaskService;
import com.fs.his.vo.*;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.TzBankService.TzBankServiceImpl.TzBankServiceImpl;
import com.fs.tzBankPay.doman.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
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.FsPrescribe;
import com.fs.his.service.IFsPrescribeService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

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

/**
 * 处方Controller
 *
 * @author fs
 * @date 2023-06-13
 */
@RestController
@RequestMapping("/his/prescribe")
public class FsPrescribeController extends BaseController
{
    @Autowired
    private IFsPrescribeService fsPrescribeService;

    @Autowired
    private IFsExportTaskService exportTaskService;
    @Autowired
    private FsPatientMapper fsPatientMapper;
    /**
     * 查询处方列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FsPrescribeParam fsPrescribe)
    {
        startPage();
        List<FsPrescribeListVO> list = fsPrescribeService.selectFsPrescribeListVO(fsPrescribe);
        for (FsPrescribeListVO vo : list){
            if (vo.getPatientTel()!=null){
                vo.setPatientTel(vo.getPatientTel().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出处方列表
     */
    @PreAuthorize("@ss.hasPermi('his:prescribe:export')")
    @Log(title = "处方", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsPrescribeParam fsPrescribe)
    {
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        if (fsPrescribeService.isEntityNull(fsPrescribe)){
            return AjaxResult.error("请筛选数据导出");
        }
        logger.info("tc>\n【导出处方】：{}", SecurityUtils.getUserId());
        Long count = fsPrescribeService.selectFsPrescribeExcelListVOCount(fsPrescribe);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(5);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("处方单导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        fsPrescribe.setTaskId(task.getTaskId());
        fsPrescribeService.exportData(fsPrescribe);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }

    /**
     * 导出医疗信息反馈单
     */
    @PreAuthorize("@ss.hasPermi('his:prescribe:messageFeedbackExport')")
    @Log(title = "医疗信息反馈单", businessType = BusinessType.EXPORT)
    @GetMapping("/messageFeedbackExport")
    public AjaxResult messageFeedbackExport(FsPrescribeParam fsPrescribe)
    {
        logger.info("tc>\n【导出医疗信息反馈单】：{}", SecurityUtils.getUserId());
        if (fsPrescribeService.isEntityNull(fsPrescribe)){
            return AjaxResult.error("请筛选数据导出");
        }
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }

        FsExportTask task=new FsExportTask();
        task.setTaskType(6);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("处方医疗反馈清单导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        fsPrescribe.setTaskId(task.getTaskId());
        fsPrescribeService.exportMessageFeedback(fsPrescribe);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());
    }

    /**
     * 获取处方详细信息
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping(value = "/{prescribeId}")
    public AjaxResult getInfo(@PathVariable("prescribeId") Long prescribeId)
    {

        FsPrescribeVO fsPrescribe = fsPrescribeService.selectFsPrescribeByPrescribeIdVO(prescribeId);
        if (fsPrescribe.getPatientTel()!=null){
            fsPrescribe.setPatientTel(fsPrescribe.getPatientTel().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
        }
        FsPatient fsPatient = fsPatientMapper.selectFsPatientByPatientId(fsPrescribe.getPatientId());
        if (fsPatient!=null&&fsPatient.getIdCard()!=null){
            fsPrescribe.setIdCard(fsPatient.getIdCard().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1**********$2"));
        }
        return AjaxResult.success(fsPrescribe);
    }

    @GetMapping(value = "/queryIdCard/{orderId}")
    @Log(title = "查看身份证", businessType = BusinessType.GRANT)
    @PreAuthorize("@ss.hasPermi('his:prescribe:queryIdCard')")
    public R getPhone(@PathVariable("orderId") Long orderId)
    {
        FsPatient fsPatient = fsPatientMapper.selectFsPatientByPatientId(orderId);
        String idCard = fsPatient.getIdCard();
        return R.ok().put("data",idCard);
    }


    /**
     * 获取处方详细信息
     */

    @GetMapping("/Drug/{prescribeId}")
    public AjaxResult getDrugInfo(@PathVariable("prescribeId") Long prescribeId)
    {
        return AjaxResult.success(fsPrescribeService.selectFsPrescribeDrugByPrescribeIdVO(prescribeId));
    }

    /**
     * 新增处方
     */
    @PreAuthorize("@ss.hasPermi('his:prescribe:add')")
    @Log(title = "处方", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsPrescribe fsPrescribe)
    {
        return toAjax(fsPrescribeService.insertFsPrescribe(fsPrescribe));
    }

    /**
     * 修改处方
     */
    @PreAuthorize("@ss.hasPermi('his:prescribe:edit')")
    @Log(title = "处方", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsPrescribe fsPrescribe)
    {
        return toAjax(fsPrescribeService.updateFsPrescribe(fsPrescribe));
    }

    /**
     * 删除处方
     */
    @PreAuthorize("@ss.hasPermi('his:prescribe:remove')")
    @Log(title = "处方", businessType = BusinessType.DELETE)
	@DeleteMapping("/{prescribeIds}")
    public AjaxResult remove(@PathVariable Long[] prescribeIds)
    {
        return toAjax(fsPrescribeService.deleteFsPrescribeByPrescribeIds(prescribeIds));
    }




}
