package com.fs.hospital.service.impl;

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

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fs.common.BeanCopyUtils;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.his.domain.FsStoreOrderItem;
import com.fs.hospital.domain.*;
import com.fs.hospital.mapper.*;
import com.fs.hospital.param.HospitalOrderCashierParam;
import com.fs.hospital.param.HospitalOrderParam;
import com.fs.hospital.vo.HospitalOrderItemListHVO;
import com.fs.hospital.vo.HospitalOrderListHVO;
import com.fs.hospital.vo.HospitalOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.hospital.service.IHospitalOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 诊疗订单Service业务层处理
 *
 * @author fs
 * @date 2024-03-22
 */
@Service
public class HospitalOrderServiceImpl implements IHospitalOrderService
{
    @Autowired
    private HospitalOrderMapper hospitalOrderMapper;

    @Autowired
    HospitalOutpatientOrderServiceImpl  hospitalOutpatientOrderService;

    @Autowired
    private HospitalOrderItemMapper hospitalOrderItemMapper;

    @Autowired
    private HospitalPharmacyOrderMapper hospitalPharmacyOrderMapper;

    @Autowired
    private HospitalPatientMapper hospitalPatientMapper;

    @Autowired
    private HospitalTreatOrderMapper treatOrderMapper;

    @Autowired
    private  HospitalExamOrderMapper hospitalExamOrderMapper;

    @Autowired
    private HospitalInspectOrderMapper hospitalInspectOrderMapper;
    /**
     * 查询诊疗订单
     *
     * @param orderId 诊疗订单主键
     * @return 诊疗订单
     */
    @Override
    public R selectHospitalOrderByOrderId(Long orderId)
    {
        HospitalOrder hospitalOrder = hospitalOrderMapper.selectHospitalOrderByOrderId(orderId);
        if (hospitalOrder != null){
            //根据订单id 查询诊疗项目单
            List<HospitalOrderItem> orderItems = hospitalOrderItemMapper.selectHospitalOrderItemByOrder(orderId);
            //整合诊疗项目单详情
            List<HospitalOrderItemListHVO> list = hospitalOutpatientOrderService.getOrderItemList(orderItems);
            return R.ok().put("order",hospitalOrder).put("list",list);
        }
        return R.error("未找到订单信息");
    }

    /**
     * 查询诊疗订单列表
     *
     * @param hospitalOrder 诊疗订单
     * @return 诊疗订单
     */
    @Override
    public List<HospitalOrder> selectHospitalOrderList(HospitalOrder hospitalOrder)
    {
        return hospitalOrderMapper.selectHospitalOrderList(hospitalOrder);
    }

    /**
     * 新增诊疗订单
     *
     * @param hospitalOrder 诊疗订单
     * @return 结果
     */
    @Override
    public int insertHospitalOrder(HospitalOrder hospitalOrder)
    {
        hospitalOrder.setCreateTime(DateUtils.getNowDate());
        return hospitalOrderMapper.insertHospitalOrder(hospitalOrder);
    }

    /**
     * 修改诊疗订单
     *
     * @param hospitalOrder 诊疗订单
     * @return 结果
     */
    @Override
    public int updateHospitalOrder(HospitalOrder hospitalOrder)
    {
        hospitalOrder.setUpdateTime(DateUtils.getNowDate());
        return hospitalOrderMapper.updateHospitalOrder(hospitalOrder);
    }

    /**
     * 批量删除诊疗订单
     *
     * @param orderIds 需要删除的诊疗订单主键
     * @return 结果
     */
    @Override
    public int deleteHospitalOrderByOrderIds(Long[] orderIds)
    {
        return hospitalOrderMapper.deleteHospitalOrderByOrderIds(orderIds);
    }

    /**
     * 删除诊疗订单信息
     *
     * @param orderId 诊疗订单主键
     * @return 结果
     */
    @Override
    public int deleteHospitalOrderByOrderId(Long orderId)
    {
        return hospitalOrderMapper.deleteHospitalOrderByOrderId(orderId);
    }

    @Override
    public List<HospitalOrderListHVO> selectHospitalOrderListHVO(HospitalOrderParam param) {
        return hospitalOrderMapper.selectHospitalOrderListHVO(param);
    }

    /**
     *  事务支付订单
     */
    @Override
    @Transactional
    public R cashier(HospitalOrderCashierParam param) {
        HospitalOrder hospitalOrder = hospitalOrderMapper.selectHospitalOrderByOrderId(param.getOrderId());
        if(hospitalOrder == null){
            return R.error("订单不存在");
        }
        int comparisonResult = hospitalOrder.getTotalMoney().compareTo(param.getPayMoney());
        if (comparisonResult!=0){
            return R.error("订单收费金额不正确");
        }
        hospitalOrder.setPayType(param.getPayType());
        hospitalOrder.setPayMoney(param.getPayMoney());
        hospitalOrder.setRemark(param.getRemark());
        hospitalOrder.setStatus(2);
        hospitalOrder.setUpdateTime(DateUtils.getNowDate());
        if (hospitalOrderMapper.updateHospitalOrder(hospitalOrder)>0){

            //查询订单的详细信息，比如药品-检查等单子
            List<HospitalOrderItem> orderItems = hospitalOrderItemMapper.selectHospitalOrderItemByOrder(hospitalOrder.getOrderId());
            boolean containsItemTypeFour = orderItems.stream()
                    .anyMatch(orderItem -> orderItem.getItemType() == 4);
            HospitalPharmacyOrder pharmacyOrder = new HospitalPharmacyOrder();
            //将相同数据copy过来，之后需要set的再set
            //BeanCopyUtils.copy(hospitalOrder,pharmacyOrder);
            pharmacyOrder.setUserId(hospitalOrder.getUserId());

            //是否是药品订单？(生成药品单)
            if (containsItemTypeFour){
                pharmacyOrder.setOrderCode("YF"+ IdUtil.getSnowflake(0, 0).nextIdStr());
                pharmacyOrder.setHospitalId(hospitalOrder.getHospitalId());
                //如何门诊订单不为空，1 门诊 2 零售
                if (hospitalOrder.getOutpatientOrderId()!=null){
                    pharmacyOrder.setOutpatientOrderId(hospitalOrder.getOutpatientOrderId());
                    pharmacyOrder.setOrderType(1);
                }else {
                    pharmacyOrder.setOrderType(2);
                }
                pharmacyOrder.setStatus(1);
                pharmacyOrder.setCreateTime(DateUtils.getNowDate());
                pharmacyOrder.setPatientId(hospitalOrder.getPatientId());
                pharmacyOrder.setPatientJson(hospitalOrder.getPatientJson());
                hospitalPharmacyOrderMapper.insertHospitalPharmacyOrder(pharmacyOrder);
            }

            //遍历订单的详情页,生成检查单，检验单的订单详情
            for (HospitalOrderItem item :orderItems){
                //检验单
                if (item.getItemType()==1){

                    //解析检验json
                    HospitalExamItem hospitalExamItem = JSON.parseObject(item.getItemJson(), HospitalExamItem.class);

                    HospitalExamOrder hospitalExamOrder= new HospitalExamOrder();

                    hospitalExamOrder.setOrderCode("JY"+IdUtil.getSnowflake(0, 0).nextIdStr());
                    hospitalExamOrder.setTitle(hospitalExamItem.getExamName());
                    hospitalExamOrder.setHospitalId(item.getHospitalId());
                    hospitalExamOrder.setOutpatientOrderId(item.getOutpatientOrderId());
                    hospitalExamOrder.setExamItemId(hospitalExamItem.getExamId());
                    hospitalExamOrder.setOrderItemId(item.getItemId());
                    hospitalExamOrder.setOrderType(1);
                    hospitalExamOrder.setUserId(hospitalOrder.getUserId());
                    hospitalExamOrder.setPatientId(hospitalOrder.getPatientId());
                    hospitalExamOrder.setPatientJson(hospitalOrder.getPatientJson());
                    hospitalExamOrder.setStatus(1);
                    hospitalExamOrder.setCreateTime(new Date());

                    hospitalExamOrderMapper.insertHospitalExamOrder(hospitalExamOrder);
                }
                //生成检查单详细记录
                if (item.getItemType()==2){

                    //解析检验json
                    HospitalInspectItem hospitalInspectItem = JSON.parseObject(item.getItemJson(), HospitalInspectItem.class);

                    HospitalInspectOrder hospitalInspectOrder= new HospitalInspectOrder();

                    hospitalInspectOrder.setOrderCode("JC"+IdUtil.getSnowflake(0, 0).nextIdStr());
                    hospitalInspectOrder.setTitle(hospitalInspectItem.getInspectName());
                    hospitalInspectOrder.setHospitalId(item.getHospitalId());
                    hospitalInspectOrder.setOutpatientOrderId(item.getOutpatientOrderId());
                    hospitalInspectOrder.setInspectItemId(hospitalInspectItem.getInspectId());
                    hospitalInspectOrder.setOrderItemId(item.getItemId());
                    hospitalInspectOrder.setOrderType(1);
                    hospitalInspectOrder.setUserId(hospitalOrder.getUserId());
                    hospitalInspectOrder.setPatientId(hospitalOrder.getPatientId());
                    hospitalInspectOrder.setPatientJson(hospitalOrder.getPatientJson());
                    hospitalInspectOrder.setStatus(1);
                    hospitalInspectOrder.setCreateTime(new Date());
                    hospitalInspectOrderMapper.insertHospitalInspectOrder(hospitalInspectOrder);

                }
            }


            for (HospitalOrderItem orderItem : orderItems){
                if (orderItem.getItemType()==4 && pharmacyOrder.getOrderId()!=null){
                    orderItem.setStatus(1);
                    orderItem.setPharmacyOrderId(pharmacyOrder.getOrderId());
                }
                orderItem.setPayStatus(2);
                orderItem.setPayMoney(orderItem.getPrice().multiply(BigDecimal.valueOf(orderItem.getCount())));
                hospitalOrderItemMapper.updateHospitalOrderItem(orderItem);
            }

        }

        return R.ok("收费完成");
    }

    /**
     * 挂单
     */
    @Override
    public int handleOrderChangeExecute(Long orderId,int type) {
        return  hospitalOrderMapper.handleOrderChangeExecute(orderId, type);
    }

    /**
     * 查询患者
     * @param patientId 患者id
     * @return 结果
     */
    @Override
    public List<HospitalOrderVO> selectHospitalOrderByPatientIdList(Long patientId,int status) {

        return  hospitalOrderMapper.selectHospitalOrderByPatientIdList(patientId,status);
    }

    @Override
    public HospitalOrderVO getFeeRecordsByOrderId(Long orderId) {
        return  hospitalOrderMapper.getFeeRecordsByOrderId(orderId);
    }

    /**
     *  完成新增收费
     */
    @Override
    public R finishOrder(HospitalOrderParam param) {
        //查询收费单
        HospitalOrder hospitalOrder = hospitalOrderMapper.selectHospitalOrderByOrderId(param.getOrderId());

        //存储患者id和json
        if (hospitalOrder!=null){
            if (hospitalOrder.getPatientId()==null){
                hospitalOrder.setPatientId(param.getPatientId());
                HospitalPatient patient = hospitalPatientMapper.selectHospitalPatientByPatientId(param.getPatientId());
                if (patient!=null){
                    hospitalOrder.setPatientJson(JSON.toJSONString(patient));
                }
            }
        }

        hospitalOrder.setTotalMoney(param.getTotalMoney());
        hospitalOrder.setOrderCode(IdUtil.getSnowflake(0, 0).nextIdStr());
        hospitalOrder.setStatus(1);
        hospitalOrder.setUserId(param.getUserId());
        hospitalOrder.setCreateTime(new Date());

        //列出治疗项目清单
        List<HospitalOrderItemListHVO> list = param.getOrderItems();
        HospitalTreatOrder treatOrder = new HospitalTreatOrder();
        if(list.size()>0&&list!=null) {
            //计算出治疗项目的总费用
            BigDecimal treatTotalMoney = list.stream()
                    .map(item -> item.getPrice() != null ? item.getPrice() : BigDecimal.ZERO)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            treatOrder.setOrderCode("ZX"+IdUtil.getSnowflake(0, 0).nextIdStr());
            treatOrder.setPatientId(param.getPatientId());
            treatOrder.setHospitalId(hospitalOrder.getHospitalId());
            treatOrder.setOrderType(2);
            treatOrder.setUserId(param.getUserId());
            treatOrder.setPatientJson(hospitalOrder.getPatientJson());
            treatOrder.setCreateTime(new Date());
            treatOrder.setStatus(2);
            treatOrder.setIsPay(0);
            treatOrder.setMoney(treatTotalMoney);
            //生成总费用单
            treatOrderMapper.insertHospitalTreatOrder(treatOrder);
            hospitalOrder.setTreatOrderId(treatOrder.getOrderId());
            //更新-关联诊疗订单
            hospitalOrderMapper.updateHospitalOrder(hospitalOrder);


            //遍历orderItem（治疗项目清单）生成订单详情
            for (HospitalOrderItemListHVO item : list) {
                HospitalOrderItem hospitalOrderItem = new HospitalOrderItem();
                hospitalOrderItem.setOrderId(hospitalOrder.getOrderId());
                if (treatOrder.getOrderId()!=null){
                    hospitalOrderItem.setTreatOrderId(treatOrder.getOrderId());
                }
                if (item.getType()==3){
                    hospitalOrderItem.setTreatStatus(0); //治疗待执行
                    hospitalOrderItem.setRemainCount(item.getCount());
                }
                hospitalOrderItem.setHospitalId(hospitalOrder.getHospitalId());
                hospitalOrderItem.setOutpatientOrderId(hospitalOrder.getOutpatientOrderId());
                hospitalOrderItem.setItemType(item.getType());
                hospitalOrderItem.setBusinessId(item.getId());
                //判断类型存项目json
                hospitalOutpatientOrderService.processItem(hospitalOrderItem, item);
                hospitalOrderItem.setCount(item.getCount());
                hospitalOrderItem.setPrice(item.getPrice());
                hospitalOrderItem.setPayStatus(1);
                //将选择的诊疗项目清单记录
                hospitalOrderItemMapper.insertHospitalOrderItem(hospitalOrderItem);
            }

            return R.ok();
        }

        return R.ok();
    }
}
