package com.fs.his.controller;

import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
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.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.his.domain.FsExportTask;
import com.fs.his.domain.FsInquiryOrder;
import com.fs.his.domain.FsInquiryOrderMsg;
import com.fs.his.domain.FsStoreOrderLogs;
import com.fs.his.param.FsInquiryOrderCancelParam;
import com.fs.his.param.FsInquiryOrderParam;
import com.fs.his.param.FsInquiryOrderRefundParam;
import com.fs.his.service.IFsExportTaskService;
import com.fs.his.service.IFsInquiryOrderLogsService;
import com.fs.his.service.IFsInquiryOrderService;
import com.fs.his.vo.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

import static com.fs.common.utils.SecurityUtils.getUserId;

/**
 * 问诊订单Controller
 *
 * @author fs
 * @date 2023-06-12
 */
@RestController
@RequestMapping("/his/inquiryOrder")
public class FsInquiryOrderController extends BaseController
{
    @Autowired
    private IFsInquiryOrderService fsInquiryOrderService;
    @Autowired
    private IFsExportTaskService exportTaskService;
    /**
     * 查询问诊订单列表
     */
    @GetMapping("/list")
   public TableDataInfo list(FsInquiryOrderParam fsInquiryOrder)
    {
        startPage();
        if(!StringUtils.isEmpty(fsInquiryOrder.getCreateTimeRange())){
            fsInquiryOrder.setCreateTimeList(fsInquiryOrder.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getPayTimeRange())){
            fsInquiryOrder.setPayTimeList(fsInquiryOrder.getPayTimeRange().split("--"));
        }
        if (getUserId().equals(54L)||getUserId().equals(211L)){
            fsInquiryOrder.setCompanyId(188L);
        }
        List<FsInquiryOrderListVO> list = fsInquiryOrderService.selectFsInquiryOrderVOList(fsInquiryOrder);
        return getDataTable(list);
    }

    /**
     * 导出问诊订单列表
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:export')")
    @Log(title = "问诊订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsInquiryOrderParam fsInquiryOrder)
    {
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        Integer inquiryType = fsInquiryOrder.getInquiryType();
        fsInquiryOrder.setInquiryType(null);
        logger.info("导出问诊订单:"+ SecurityUtils.getUserId());
        if (fsInquiryOrderService.isEntityNull(fsInquiryOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        fsInquiryOrder.setInquiryType(inquiryType);
        if(!StringUtils.isEmpty(fsInquiryOrder.getCreateTimeRange())){
            fsInquiryOrder.setCreateTimeList(fsInquiryOrder.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getPayTimeRange())){
            fsInquiryOrder.setPayTimeList(fsInquiryOrder.getPayTimeRange().split("--"));
        }
        if (getUserId().equals(54L)||getUserId().equals(211L)){
            fsInquiryOrder.setCompanyId(188L);
        }

        Long count =fsInquiryOrderService.selectFsInquiryOrderExcelListVOCount(fsInquiryOrder);
        System.out.println("传参"+fsInquiryOrder);
        System.out.println("数量"+count);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(7);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("问诊导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrder.setTaskId(task.getTaskId());
        fsInquiryOrderService.exportData(fsInquiryOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());


    }

    /**
     * 导出问诊订单列表
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:messageFeedbackExport')")
    @Log(title = "问诊订单", businessType = BusinessType.EXPORT)
    @GetMapping("/messageFeedbackExport")
    public AjaxResult messageFeedbackExport(FsInquiryOrderParam fsInquiryOrder)
    {
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        logger.info("导出问诊订单:"+ SecurityUtils.getUserId());
        if (fsInquiryOrderService.isEntityNull(fsInquiryOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(8);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("问诊导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrder.setTaskId(task.getTaskId());
        if (getUserId().equals(54L)||getUserId().equals(211L)){
            fsInquiryOrder.setCompanyId(188L);
        }
        fsInquiryOrderService.exportFeedbackData(fsInquiryOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }


    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:sendMsg')")
    @GetMapping(value = "/sendMsg/{orderId}")
    public AjaxResult sendMsg(@PathVariable("orderId") Long orderId)
    {
        ;
        return AjaxResult.success(fsInquiryOrderService.sendStartMsg(orderId));
    }
    /**
     * 获取问诊订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        FsInquiryOrderVO fsInquiryOrderVO = fsInquiryOrderService.selectFsInquiryOrderVOByOrderId(orderId);
        String patientJson = fsInquiryOrderVO.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){
                parse.put("mobile",mobile.replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }

            String s = JSON.toJSONString(parse);
            fsInquiryOrderVO.setPatientJson(s);
        }
        return AjaxResult.success(fsInquiryOrderVO);
    }

    /**
     * 新增问诊订单
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:add')")
    @Log(title = "问诊订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsInquiryOrder fsInquiryOrder)
    {
        return toAjax(fsInquiryOrderService.insertFsInquiryOrder(fsInquiryOrder));
    }

    /**Fs
     * 修改问诊订单
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:edit')")
    @Log(title = "问诊订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsInquiryOrder fsInquiryOrder)
    {
        return toAjax(fsInquiryOrderService.updateFsInquiryOrder(fsInquiryOrder));
    }

    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:editStatus')")
    @Log(title = "问诊订单", businessType = BusinessType.UPDATE)
    @PutMapping("/editStatus")
    public AjaxResult editStatus(@RequestBody FsInquiryOrder fsInquiryOrder)
    {
        FsInquiryOrder order = new FsInquiryOrder();
        order.setOrderId(fsInquiryOrder.getOrderId());
        order.setStatus(fsInquiryOrder.getStatus());
        return toAjax(fsInquiryOrderService.updateFsInquiryOrder(fsInquiryOrder));
    }



    @Transactional
    @RepeatSubmit
    @ApiOperation("取消订单")
    @PostMapping("/cancelOrder")
    public R cancelOrder(@Validated @RequestBody FsInquiryOrderCancelParam param ){
        param.setType(4);
        logger.info("取消问诊订单:"+param.getOrderId()+":操作人:总后台:"+ SecurityUtils.getUsername());
        return fsInquiryOrderService.cancelOrder(param);
    }


    @Transactional
    @RepeatSubmit
    @ApiOperation("退款订单")
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:refundOrder')")
    @PostMapping("/refundOrder")
    public R refundOrder(@Validated @RequestBody FsInquiryOrderRefundParam param){
        param.setSysUserName(getLoginUser().getUsername());
        logger.info("退款问诊订单:"+param.getOrderId()+":操作人:总后台:"+ getLoginUser().getUsername());
        return fsInquiryOrderService.refundOrder(param);
    }


    /**
     * 删除问诊订单
     */
    @PreAuthorize("@ss.hasPermi('his:inquiryOrder:remove')")
    @Log(title = "问诊订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(fsInquiryOrderService.deleteFsInquiryOrderByOrderIds(orderIds));
    }




    @GetMapping("/msgList")
    public TableDataInfo msgList(Long orderId)
    {
        startPage();
        List<FsInquiryOrderMsg> list = fsInquiryOrderService.selectFsInquiryOrderMsgByOrderId(orderId);
        return getDataTable(list);
    }


    /**
     * 查询订单log列表
     */
    @GetMapping("/logList/{orderId}")
    public TableDataInfo logList(@PathVariable("orderId") String orderId)
    {
        List<FsStoreOrderLogs> list = fsInquiryOrderService.selectFsInquiryOrderLogsList(orderId);
        return getDataTable(list);
    }




}
