package com.fs.company.controller.store;

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.StringUtils;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
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.IFsDoctorService;
import com.fs.his.service.IFsExportTaskService;
import com.fs.his.service.IFsInquiryOrderLogsService;
import com.fs.his.service.IFsInquiryOrderService;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsInquiryOrderListVO;
import com.fs.his.vo.FsInquiryOrderVO;
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;

/**
 * 问诊订单Controller
 *
 * @author fs
 * @date 2023-06-12
 */
@RestController
@RequestMapping("/store/inquiryOrder")
public class FsInquiryOrderController extends BaseController
{
    @Autowired
    private IFsInquiryOrderService fsInquiryOrderService;
    @Autowired
    private IFsInquiryOrderLogsService fsInquiryOrderLogsService;

    @Autowired
    private IFsDoctorService fsDoctorService;

    @Autowired
    private IFsExportTaskService exportTaskService;
    /**
     * 查询问诊订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:list')")
    @GetMapping("/list")
   public TableDataInfo list(FsInquiryOrderParam fsInquiryOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsInquiryOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        if(!StringUtils.isEmpty(fsInquiryOrder.getCreateTimeRange())){
            fsInquiryOrder.setCreateTimeList(fsInquiryOrder.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getPayTimeRange())){
            fsInquiryOrder.setPayTimeList(fsInquiryOrder.getPayTimeRange().split("--"));
        }
        List<FsInquiryOrderListVO> list = fsInquiryOrderService.selectFsInquiryOrderVOList(fsInquiryOrder);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:myList')")
    @GetMapping("/myList")
    public TableDataInfo myList(FsInquiryOrderParam fsInquiryOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsInquiryOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        fsInquiryOrder.setCompanyUserId(loginUser.getUser().getUserId());
        if(!StringUtils.isEmpty(fsInquiryOrder.getCreateTimeRange())){
            fsInquiryOrder.setCreateTimeList(fsInquiryOrder.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getPayTimeRange())){
            fsInquiryOrder.setPayTimeList(fsInquiryOrder.getPayTimeRange().split("--"));
        }
        List<FsInquiryOrderListVO> list = fsInquiryOrderService.selectFsInquiryOrderVOList(fsInquiryOrder);
        return getDataTable(list);
    }
    /**
     * 导出问诊订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:export')")
    @Log(title = "问诊订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsInquiryOrderParam fsInquiryOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsInquiryOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        Long userId = loginUser.getUser().getUserId();
        logger.info("tc>\n【导出问诊订单】："+ userId);
        if (fsInquiryOrderService.isEntityNull(fsInquiryOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getCreateTimeRange())){
            fsInquiryOrder.setCreateTimeList(fsInquiryOrder.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getPayTimeRange())){
            fsInquiryOrder.setPayTimeList(fsInquiryOrder.getPayTimeRange().split("--"));
        }
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        Long count =fsInquiryOrderService.selectFsInquiryOrderExcelListVOCount(fsInquiryOrder);
        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(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrder.setTaskId(task.getTaskId());
        fsInquiryOrderService.exportData(fsInquiryOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }

    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:myExport')")
    @Log(title = "问诊订单", businessType = BusinessType.EXPORT)
    @GetMapping("/myExport")
    public AjaxResult myExport(FsInquiryOrderParam fsInquiryOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUser().getUserId();
        logger.info("tc>\n【导出问诊订单】："+ userId);
        if (fsInquiryOrderService.isEntityNull(fsInquiryOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getCreateTimeRange())){
            fsInquiryOrder.setCreateTimeList(fsInquiryOrder.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(fsInquiryOrder.getPayTimeRange())){
            fsInquiryOrder.setPayTimeList(fsInquiryOrder.getPayTimeRange().split("--"));
        }
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        fsInquiryOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        fsInquiryOrder.setCompanyUserId(loginUser.getUser().getUserId());
        Long count =fsInquiryOrderService.selectFsInquiryOrderExcelListVOCount(fsInquiryOrder);
        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(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrder.setTaskId(task.getTaskId());
        fsInquiryOrderService.exportData(fsInquiryOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }

    /**
     * 导出问诊订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:messageFeedbackExport')")
    @Log(title = "问诊反馈", businessType = BusinessType.EXPORT)
    @GetMapping("/messageFeedbackExport")
    public AjaxResult messageFeedbackExport(FsInquiryOrderParam fsInquiryOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUser().getUserId();

        logger.info("tc>\n【导出问诊反馈】："+ userId);
        if (fsInquiryOrderService.isEntityNull(fsInquiryOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        fsInquiryOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        Long count =fsInquiryOrderService.selectFsInquiryFeedbackExportListVOCount(fsInquiryOrder);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(8);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("问诊信息反馈单导出");
        task.setSysType(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        fsInquiryOrder.setTaskId(task.getTaskId());
        fsInquiryOrderService.exportFeedbackData(fsInquiryOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }


    /**
     * 获取问诊订单详细信息
     */

    @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){
                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);
            fsInquiryOrderVO.setPatientJson(s);
        }
        return AjaxResult.success(fsInquiryOrderVO);
    }

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

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

    @Log(title = "填写备注", businessType = BusinessType.UPDATE)
    @PostMapping("/writeRemark")
    public AjaxResult writeRemark(@RequestBody FsInquiryOrder fsInquiryOrder)
    {
        return toAjax(fsInquiryOrderService.updateFsInquiryOrder(fsInquiryOrder));
    }

    @PreAuthorize("@ss.hasPermi('store: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(5);
        return fsInquiryOrderService.cancelOrder(param);
    }


    @Transactional
    @RepeatSubmit
    @ApiOperation("退款订单")
    @PostMapping("/refundOrder")
    public R refundOrder(@Validated @RequestBody FsInquiryOrderRefundParam param){
        param.setSysUserName(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);
    }

    @GetMapping(value = "/doctor/{doctorId}")
    public AjaxResult doctor(@PathVariable("doctorId") Long doctorId)
    {
        return AjaxResult.success(fsDoctorService.selectFsDoctorVOByDoctorId(doctorId));
    }


}
