package com.fs.app.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.common.core.domain.R;
import com.fs.common.utils.StringUtils;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.his.domain.*;
import com.fs.his.dto.FsInquiryOrderPatientDTO;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.vo.FsDoctorPrescribeListDVO;
import com.fs.his.vo.FsPrescribeListDVO;
import com.fs.im.service.IImService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;


@Api("处方接口")
@RestController
@RequestMapping(value="/app/prescribe")
public class PrescribeController extends  AppBaseController {

    @Autowired
    private IFsPrescribeService prescribeService;


    @Autowired
    private IFsPrescribeDrugService prescribeDrugService;
    @Autowired
    private IFsDoctorService doctorService;
    @Autowired
    private IFsDoctorPrescribeService doctorPrescribeService;
    @Autowired
    private IFsDoctorPrescribeDrugService doctorPrescribeDrugService;
    @Autowired
    private IFsInquiryOrderService inquiryOrderService;
    @Autowired
    private IFsStoreOrderService storeOrderService;
    @Autowired
    private IImService imService;

    @Login
    @GetMapping("/getDoctorPrescribeList")
    public R getDoctorPrescribeList(FsDoctorPrescribeListDParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setDoctorId(Long.parseLong(getDoctorId()));
        List<FsDoctorPrescribeListDVO> list=doctorPrescribeService.selectFsDoctorPrescribeListDVO(param);
        PageInfo<FsDoctorPrescribeListDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }


    @Login
    @GetMapping("/getPrescribeList")
    public R getPrescribeList(FsPrescribeListDParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setDoctorId(Long.parseLong(getDoctorId()));
        param.setDoctorDrugId(Long.parseLong(getDoctorId()));
        List<FsPrescribeListDVO> list=prescribeService.selectFsPrescribeListDVO(param);
        PageInfo<FsPrescribeListDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }


    @Login
    @GetMapping("/getPrescribeById")
    public R getPrescribeById(@RequestParam("prescribeId")Long prescribeId)
    {
        FsPrescribe prescribe=prescribeService.selectFsPrescribeByPrescribeId(prescribeId);
        FsPrescribeDrug map=new FsPrescribeDrug();
        map.setPrescribeId(prescribeId);
        List<FsPrescribeDrug> drugs=prescribeDrugService.selectFsPrescribeDrugList(map);
        FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(prescribe.getDoctorId());
        Map<String,Object> maps=new HashMap<>();
        maps.put("prescribe",prescribe);
        maps.put("drugs",drugs);
        maps.put("doctor",doctor);
        return R.ok().put("data",maps);
    }


    @Login
    @ApiOperation("审核处方")
    @PostMapping("/audit")
    @Synchronized
    public R audit(@Validated @RequestBody FsPrescribeAuditParam param, HttpServletRequest request){
        param.setDoctorId(Long.parseLong(getDoctorId()));
        return prescribeService.audit(param);
    }



    @Login
    @GetMapping("/getDoctorPrescribeById")
    public R getDoctorPrescribeById(@RequestParam("prescribeId")Long prescribeId)
    {
        FsDoctorPrescribe prescribe=doctorPrescribeService.selectFsDoctorPrescribeByPrescribeId(prescribeId);
        FsDoctorPrescribeDrug map=new FsDoctorPrescribeDrug();
        map.setPrescribeId(prescribeId);
        List<FsDoctorPrescribeDrug> drugs=doctorPrescribeDrugService.selectFsDoctorPrescribeDrugList(map);
        Map<String,Object> maps=new HashMap<>();
        maps.put("prescribe",prescribe);
        maps.put("drugs",drugs);
        return R.ok().put("data",maps);
    }
    @Login
    @ApiOperation("删除处方")
    @PostMapping("/delDoctorPrescribe")
    public R delDoctorPrescribe(@Validated @RequestBody FsDoctorPrescribeDelParam param, HttpServletRequest request){
        FsDoctorPrescribe prescribe=doctorPrescribeService.selectFsDoctorPrescribeByPrescribeId(param.getPrescribeId());
        if(!prescribe.getDoctorId().equals(Long.parseLong(getDoctorId()))){
            return R.error("非法操作");
        }
        doctorPrescribeService.deleteFsDoctorPrescribeByPrescribeId(param.getPrescribeId());
        doctorPrescribeDrugService.deleteFsDoctorPrescribeDrugByPrescribe(param.getPrescribeId());
        return R.ok("操作成功");
    }

    @Login
    @ApiOperation("添加处方")
    @PostMapping("/addPrescribe")
    public R addPrescribe(@Validated @RequestBody FsDoctorPrescribeAddEditParam param, HttpServletRequest request){

        FsDoctorPrescribe doctorPrescribe=new FsDoctorPrescribe();
        BeanUtils.copyProperties(param,doctorPrescribe);
        doctorPrescribe.setDoctorId(Long.parseLong(getDoctorId()));
        doctorPrescribeService.insertFsDoctorPrescribe(doctorPrescribe);
        HashSet<Long> set = new HashSet<>();
        List<FsDoctorPrescribeDrug> drugs = param.getDrugs();
        for (FsDoctorPrescribeDrug drug : drugs) {
            if (!set.add(drug.getProductId())) {
                return R.error("存在重复药品");
            }
        }

        for(FsDoctorPrescribeDrug drug:drugs){
            drug.setPrescribeId(doctorPrescribe.getPrescribeId());
            doctorPrescribeDrugService.insertFsDoctorPrescribeDrug(drug);
        }
        return R.ok("操作成功");
    }

    @Login
    @ApiOperation("编辑处方")
    @PostMapping("/editPrescribe")
    public R editPrescribe(@Validated @RequestBody FsDoctorPrescribeAddEditParam param, HttpServletRequest request){
        FsDoctorPrescribe prescribe=doctorPrescribeService.selectFsDoctorPrescribeByPrescribeId(param.getPrescribeId());
        List<FsDoctorPrescribeDrug> drugs = param.getDrugs();
        HashSet<Long> set = new HashSet<>();
        for (FsDoctorPrescribeDrug drug : drugs) {
            if (!set.add(drug.getProductId())) {
                return R.error("存在重复药品");
            }
        }
        BeanUtils.copyProperties(param,prescribe);
        prescribe.setDoctorId(Long.parseLong(getDoctorId()));
        doctorPrescribeService.updateFsDoctorPrescribe(prescribe);
        doctorPrescribeDrugService.deleteFsDoctorPrescribeDrugByPrescribe(param.getPrescribeId());

        for(FsDoctorPrescribeDrug drug:drugs){
            drug.setPrescribeId(prescribe.getPrescribeId());
            doctorPrescribeDrugService.insertFsDoctorPrescribeDrug(drug);
        }
        return R.ok("操作成功");
    }
    @Login
    @ApiOperation("创建处方")
    @Transactional
    @PostMapping("/createPrescribe")
    public R createPrescribe(@Validated @RequestBody FsPrescribeCreateParam param, HttpServletRequest request){

        //获取问诊单
        FsInquiryOrder inquiryOrder=inquiryOrderService.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(inquiryOrder!=null){
            if(!inquiryOrder.getStatus().equals(3)){
                return R.error("非法操作");
            }
            FsDoctorPrescribe doctorPrescribe=doctorPrescribeService.selectFsDoctorPrescribeByPrescribeId(param.getPrescribeId());
            FsDoctorPrescribeDrug map=new FsDoctorPrescribeDrug();
            map.setPrescribeId(param.getPrescribeId());
            List<FsDoctorPrescribeDrug> doctorPrescribeDrugs=doctorPrescribeDrugService.selectFsDoctorPrescribeDrugList(map);
            String orderSn =  OrderCodeUtils.getOrderSn();
            if(StringUtils.isEmpty(orderSn)){
                return R.error("订单生成失败，请重试");
            }
            FsPrescribe prescribe=new FsPrescribe();
            BeanUtils.copyProperties(doctorPrescribe,prescribe);
            prescribe.setInquiryOrderId(inquiryOrder.getOrderId());
            prescribe.setUserId(inquiryOrder.getUserId());
            prescribe.setPatientId(inquiryOrder.getPatientId());
            prescribe.setPrescribeCode(orderSn);
            prescribe.setIcdCode(doctorPrescribe.getIcdCode());
            FsInquiryOrderPatientDTO patientDTO= JSONUtil.toBean(inquiryOrder.getPatientJson(),FsInquiryOrderPatientDTO.class);
            prescribe.setPatientAge(patientDTO.getAge());
            prescribe.setPatientName(patientDTO.getPatientName());
            prescribe.setPatientAge(patientDTO.getAge());
            prescribe.setPatientDescs(patientDTO.getTitle());
            prescribe.setPatientTel(patientDTO.getMobile());
            prescribe.setPatientGender(patientDTO.getSex().toString());
            prescribe.setPatientBirthday(patientDTO.getBirthday());
            prescribe.setRecordPic(inquiryOrder.getImgs());
            prescribe.setDiagnose(prescribe.getDiagnose());
            prescribe.setDoctorId(inquiryOrder.getDoctorId());
            prescribe.setStatus(0);
            prescribe.setUsageJson(prescribe.getUsageJson());
            prescribe.setCycle(doctorPrescribe.getCycle());
            prescribe.setRemark(prescribe.getRemark());
            if (inquiryOrder.getSource()!=null){
                prescribe.setSource(inquiryOrder.getSource());
            }
            FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(Long.parseLong(getDoctorId()));
            if(doctor!=null&&StringUtils.isNotEmpty(doctor.getSignUrl())){
                prescribe.setDoctorSignUrl(doctor.getSignUrl());
            }
            if(doctor!=null&&doctor.getIsPrescribeDoctor()!=null&&doctor.getIsPrescribeDoctor()==1){
                prescribe.setPrescribeDoctorId(doctor.getDoctorId());
                prescribe.setPrescribeDoctorSignUrl(doctor.getSignUrl());
            }
            else{
                if(doctor.getPrescribeDoctorId()!=null){
                    FsDoctor prescribeDoctor=doctorService.selectFsDoctorByDoctorId(doctor.getPrescribeDoctorId());
                    if(prescribeDoctor!=null){
                        prescribe.setPrescribeDoctorId(prescribeDoctor.getDoctorId());
                        prescribe.setPrescribeDoctorSignUrl(prescribeDoctor.getSignUrl());
                    }
                }
            }
            if(prescribeService.insertFsPrescribe(prescribe)>0){
                //写入药品
                for(FsDoctorPrescribeDrug drug : doctorPrescribeDrugs){
                    FsPrescribeDrug prescribeDrug=new FsPrescribeDrug();
                    BeanUtils.copyProperties(drug,prescribeDrug);
                    prescribeDrug.setProductAttrValueId(drug.getProductAttrValueId());
                    prescribeDrug.setPrescribeId(prescribe.getPrescribeId());
                    prescribeDrugService.insertFsPrescribeDrug(prescribeDrug);
                }

                return R.ok("操作成功").put("prescribe",prescribe);
            }
            else{
                return R.error("操作失败");
            }
        }
        else {
            return R.error("订单不存在");
        }


    }


    @Login
    @GetMapping("/getPrescribeImg")
    public R getPrescribeImg(@RequestParam("prescribeId")Long prescribeId)
    {
        String url=prescribeService.getPrescribeCodeUrl(prescribeId);
        return R.ok().put("url",url);
    }
}
