package com.fs.app.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.app.annotation.Login;
import com.fs.app.param.InquiryOrderMsgListParam;
import com.fs.common.BeanCopyUtils;
import com.fs.common.annotation.Log;
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.ip.IpUtils;
import com.fs.company.service.ICompanyService;
import com.fs.core.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.his.domain.*;
import com.fs.his.dto.FsInquiryOrderPatientDTO;
import com.fs.his.enums.FsInquiryOrderStatusEnum;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.vo.*;
import com.fs.im.dto.MsgCustomDTO;
import com.fs.im.dto.MsgDTO;
import com.fs.im.dto.MsgDataDTO;
import com.fs.im.dto.MsgDataFormatDTO;
import com.fs.im.service.IImService;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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


@Api("订单接口")
@RestController
@RequestMapping(value="/app/inquiryOrder")
public class InquiryOrderController extends  AppBaseController {
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private IFsInquiryOrderService inquiryOrderService;
    @Autowired
    private IFsInquiryOrderMsgService inquiryOrderMsgService;
    @Autowired
    private IFsDoctorService doctorService;
    @Autowired
    private IFsInquiryOrderPingService inquiryOrderPingService;
    @Autowired
    private IFsHospitalService hospitalService;
    @Autowired
    private IFsDepartmentService departmentService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IFsUserService userService;
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private IFsIllnessLibraryService illnessLibraryService;
    @Autowired
    private IFsInquiryOrderReportService orderReportService;
    @Autowired
    private IImService imService;

    @Login
    @GetMapping("/getInquiryOrderList")
    public R getInquiryOrderList(FsInquiryOrderListPDParam param)
    {
        FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(Long.parseLong(getDoctorId()));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setDoctorId(Long.parseLong(getDoctorId()));
        param.setIsAccept(doctor.getIsAccept());
        param.setIsSelf(doctor.getIsSelf());
        List<FsInquiryOrderListPDVO> list = inquiryOrderService.selectFsInquiryOrderListPDVO(param);
        for (FsInquiryOrderListPDVO fsInquiryOrderListPDVO : list) {
            String patientJson = fsInquiryOrderListPDVO.getPatientJson();
            if (patientJson != null&&!"".equals(patientJson)) {
                FsInquiryOrderPatientDTO fsInquiryOrderPatientDTO = JSON.parseObject(patientJson, FsInquiryOrderPatientDTO.class);
                if(fsInquiryOrderPatientDTO.getMobile()!=null&&!"".equals(fsInquiryOrderPatientDTO.getMobile())){
                      fsInquiryOrderPatientDTO.setMobile(fsInquiryOrderPatientDTO.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    fsInquiryOrderListPDVO.setPatientJson(JSON.toJSONString(fsInquiryOrderPatientDTO));
                }

            }
        }
        PageInfo<FsInquiryOrderListPDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @GetMapping("/getInquiryOrderDetailsByOrderId")
    public R getInquiryOrderDetailsByOrderId(@RequestParam("orderId")Long orderId)
    {
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(orderId);
        return R.ok().put("data",order);
    }


    @GetMapping("/getCompanyList")
    public R getCompanyList()
    {
        List<OptionsVO> list = companyService.selectAllCompanyList();
        return R.ok().put("list",list);
    }
    @Login
    @GetMapping("/getInquiryOrderById")
    public R getInquiryOrderById(@RequestParam("orderId")Long orderId)
    {
        Map<String,Object> maps=new HashMap<>();
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(orderId);
        if (order.getPatientJson() != null&&!"".equals(order.getPatientJson())) {
            FsInquiryOrderPatientDTO fsInquiryOrderPatientDTO = JSON.parseObject(order.getPatientJson(), FsInquiryOrderPatientDTO.class);
            if(fsInquiryOrderPatientDTO.getMobile()!=null&&!"".equals(fsInquiryOrderPatientDTO.getMobile())){
                fsInquiryOrderPatientDTO.setMobile(fsInquiryOrderPatientDTO.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                order.setPatientJson(JSON.toJSONString(fsInquiryOrderPatientDTO));
            }

        }
        maps.put("order",order);
        if(order.getDoctorId()!=null){
            FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(order.getDoctorId());
            if(doctor!=null){
                FsHospital hospital=hospitalService.selectFsHospitalByHospitalId(doctor.getHospitalId());
                FsDepartment department=departmentService.selectFsDepartmentByDeptId(doctor.getDeptId());
                maps.put("hospital",hospital);
                maps.put("department",department);
            }
            maps.put("doctor",doctor);
        }
        FsInquiryOrderReport report=orderReportService.selectFsInquiryOrderReportByOrderId(orderId);
        maps.put("report",report);
        return R.ok().put("data",maps);
    }

//    @Login
//    @GetMapping("/getMyInquiryOrderPingList")
//    public R getMyInquiryOrderPingList(FsInquiryOrderPingListUParam param)
//    {
//
//        PageHelper.startPage(param.getPageNum(), param.getPageSize());
//        param.setUserId(Long.parseLong(getUserId()));
//        List<FsInquiryOrderPingListUVO> list=inquiryOrderPingService.selectFsInquiryOrderPingListUVO(param);
//        PageInfo<FsInquiryOrderPingListUVO> listPageInfo=new PageInfo<>(list);
//        return R.ok().put("data",listPageInfo);
//    }


    @Login
    @ApiOperation("抢单")
    @PostMapping("/acceptOrder")
    public R acceptOrder(@Validated @RequestBody FsInquiryOrderAcceptParam param, HttpServletRequest request){
        param.setDoctorId(Long.parseLong(getDoctorId()));
        return inquiryOrderService.acceptOrder(param);
    }

    @Login
    @ApiOperation("接单")
    @PostMapping("/receiveOrder")
    public R receiveOrder(@Validated @RequestBody FsInquiryOrderReceiveParam param, HttpServletRequest request){
        param.setDoctorId(Long.parseLong(getDoctorId()));
        return inquiryOrderService.receiveOrder(param);
    }

    @Login
    @ApiOperation("拒单")
    @PostMapping("/refuseOrder")
    public R refuseOrder(@Validated @RequestBody FsInquiryOrderRefuseParam param, HttpServletRequest request){
        param.setDoctorId(Long.parseLong(getDoctorId()));
        logger.info("拒单问诊订单:"+param.getOrderId()+":操作人:医生:"+ Long.parseLong(getDoctorId()));
        return inquiryOrderService.refuseOrder(param);
    }
    @Login
    @ApiOperation("完成订单")
    @PostMapping("/finishOrder")
    public R finishOrder(@Validated @RequestBody FsInquiryOrderFinishParam param, HttpServletRequest request){
        param.setDoctorId(Long.parseLong(getDoctorId()));
        return inquiryOrderService.finishOrder(param);
    }

    @Login
    @ApiOperation("评价列表")
    @GetMapping("/getInquiryOrderPingList")
    public R getInquiryOrderPingList(FsInquiryOrderPingListDParam param)
    {

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setDoctorId(Long.parseLong(getDoctorId()));
        List<FsInquiryOrderPingListDVO> list=inquiryOrderPingService.selectFsInquiryOrderPingListDVO(param);
        PageInfo<FsInquiryOrderPingListDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }



    @PutMapping("/updateRemark")
    public R edit(@RequestBody FsInquiryOrder fsInquiryOrder)
    {
        FsInquiryOrder o = new FsInquiryOrder();
        o.setOrderId(fsInquiryOrder.getOrderId());
        o.setDoctorRemark(fsInquiryOrder.getDoctorRemark());
        inquiryOrderService.updateFsInquiryOrder(o);
        return R.ok();
    }

    @Login
    @GetMapping("/getIllnessLibraryList")
    public R getIllnessLibraryList(FsIllnessLibraryListDParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsIllnessLibraryListDVO>  list=illnessLibraryService.selectFsIllnessLibraryListDVO(param);
        PageInfo<FsIllnessLibraryListDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }
    @Login
    @ApiOperation("获取诊断报告")
    @GetMapping("/getInquiryOrderReport")
    public R getInquiryOrderReport(@RequestParam("orderId")Long orderId)
    {
        FsInquiryOrderReport report=orderReportService.selectFsInquiryOrderReportByOrderId(orderId);
        return R.ok().put("data",report);
    }


    @Login
    @ApiOperation("提交诊断报告")
    @PostMapping("/submitInquiryOrderReport")
    @Transactional
    public R submitInquiryOrderReport(@Validated @RequestBody FsInquiryOrderReportSubmitDParam param, HttpServletRequest request){
        FsInquiryOrderReport report=null;
        if(param.getReportId()!=null&&param.getReportId()>0){
            report=orderReportService.selectFsInquiryOrderReportByReportId(param.getReportId());
            if(report.getStatus()==2){
                return R.error("已提交报告");
            }
            BeanCopyUtils.copy(param,report);
            report.setDoctorId(Long.parseLong(getDoctorId()));
            report.setStatus(2);
            FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(report.getDoctorId());
            if(StringUtils.isNotEmpty(doctor.getSignUrl())){
                report.setDoctorSignUrl(doctor.getSignUrl());
            }
            orderReportService.updateFsInquiryOrderReport(report);
        }
        else{
            FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(param.getOrderId());
            report=new FsInquiryOrderReport();
            BeanCopyUtils.copy(param,report);
            String reportSn =  OrderCodeUtils.getOrderSn();
            if(StringUtils.isEmpty(reportSn)){
                return R.error("订单生成失败，请重试");
            }
            report.setReportSn(reportSn);
            report.setDoctorId(Long.parseLong(getDoctorId()));
            report.setRemark(param.getRemark());
            report.setStatus(2);
            report.setOrderId(order.getOrderId());
            report.setUserId(order.getUserId());
            report.setPatientId(order.getPatientId());
            report.setPatientJson(order.getPatientJson());
            FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(report.getDoctorId());
            if(StringUtils.isNotEmpty(doctor.getSignUrl())){
                report.setDoctorSignUrl(doctor.getSignUrl());
            }

            orderReportService.insertFsInquiryOrderReport(report);

        }
        FsInquiryOrder inquiryOrder=inquiryOrderService.selectFsInquiryOrderByOrderId(report.getOrderId());
        MsgDTO msgDTO=new MsgDTO();
        msgDTO.setFrom_Account("D-"+report.getDoctorId().toString());
        msgDTO.setTo_Account("U-"+report.getUserId().toString());
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("startInquiry");
        customDTO.setImType(1);
        customDTO.setOrderType(inquiryOrder.getOrderType());
        customDTO.setOrderId(report.getOrderId().toString());
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        String ext= JSONUtil.toJsonStr(report);
        String orderId=report.getOrderId().toString();
        msg.setMsgContent(new MsgDataFormatDTO("report",ext,orderId));
        msg.setMsgType("TIMCustomElem");//TIMCustomElem
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        imService.sendMsg(msgDTO);
        return R.ok("操作成功");
    }

    @GetMapping("/getInquiryOrderMsgList")
    public R getInquiryOrderMsgList(FsInquiryOrderMsgListDParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsInquiryOrderMsgListDVO> list = inquiryOrderMsgService.selectFsInquiryOrderMsgListDVO(param);
        PageInfo<FsInquiryOrderMsgListDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }


    @GetMapping(value = "/queryPhone/{orderId}")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    public R getPhone(@PathVariable("orderId") Long orderId)
    {
        FsInquiryOrder fsInquiryOrder = inquiryOrderService.selectFsInquiryOrderByOrderId(orderId);
        String patientJson = fsInquiryOrder.getPatientJson();
        if (patientJson != null&&!"".equals(patientJson)) {
            FsInquiryOrderPatientDTO fsInquiryOrderPatientDTO = JSON.parseObject(patientJson, FsInquiryOrderPatientDTO.class);
            String phone = fsInquiryOrderPatientDTO.getMobile();
            if (phone!=null&&phone.length()>11){
               phone= decryptPhone(phone);
            }

            return R.ok().put("data",phone);
        }
        return R.ok().put("data","");
    }
}
