package com.fs.store.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fs.common.config.FSSysConfig;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.OrderUtils;
import com.fs.common.utils.StringUtils;
import com.fs.store.bean.Drug;
import com.fs.store.bean.DrugV2;
import com.fs.store.bean.Prescribe;
import com.fs.store.bean.PrescribeV2;
import com.fs.store.domain.*;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.FsPrescribeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.store.mapper.FsPrescribeMapper;

/**
 * 处方Service业务层处理
 *
 * @author fs
 * @date 2022-03-15
 */
@Service
public class FsPrescribeServiceImpl implements IFsPrescribeService
{
    @Autowired
    IPrescribeService prescribeService;
    @Autowired
    FsPrescribeMapper fsPrescribeMapper;
    @Autowired
    IFsStoreOrderService orderService;
    @Autowired
    IFsPatientService patientService;
    @Autowired
    IFsUserService userService;
    @Autowired
    FSSysConfig fsSysConfig;
    @Autowired
    IFsStoreOrderItemService orderItemService;
    @Autowired
    IFsStoreProductService productService;

    /**
     * 查询处方
     *
     * @param prescribeId 处方ID
     * @return 处方
     */
    @Override
    public FsPrescribe selectFsPrescribeById(Long prescribeId)
    {
        return fsPrescribeMapper.selectFsPrescribeById(prescribeId);
    }

    /**
     * 查询处方列表
     *
     * @param fsPrescribe 处方
     * @return 处方
     */
    @Override
    public List<FsPrescribe> selectFsPrescribeList(FsPrescribe fsPrescribe)
    {
        return fsPrescribeMapper.selectFsPrescribeList(fsPrescribe);
    }

    /**
     * 新增处方
     *
     * @param fsPrescribe 处方
     * @return 结果
     */
    @Override
    public int insertFsPrescribe(FsPrescribe fsPrescribe)
    {
        fsPrescribe.setCreateTime(DateUtils.getNowDate());
        return fsPrescribeMapper.insertFsPrescribe(fsPrescribe);
    }

    /**
     * 修改处方
     *
     * @param fsPrescribe 处方
     * @return 结果
     */
    @Override
    public int updateFsPrescribe(FsPrescribe fsPrescribe)
    {
        return fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
    }

    /**
     * 批量删除处方
     *
     * @param prescribeIds 需要删除的处方ID
     * @return 结果
     */
    @Override
    public int deleteFsPrescribeByIds(Long[] prescribeIds)
    {
        return fsPrescribeMapper.deleteFsPrescribeByIds(prescribeIds);
    }

    /**
     * 删除处方信息
     *
     * @param prescribeId 处方ID
     * @return 结果
     */
    @Override
    public int deleteFsPrescribeById(Long prescribeId)
    {
        return fsPrescribeMapper.deleteFsPrescribeById(prescribeId);
    }

    @Override
    public R doPrescribe(long userId, FsPrescribeParam param) {
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if(order==null){
            throw  new CustomException("订单不存在");
        }
//      if(order.getStatus()!=1){
//           throw  new CustomException("未支付订单不能开处方");
//      }
        FsPrescribe checkPrescribe=fsPrescribeMapper.selectFsPrescribeByOrderId(order.getId());
        if(checkPrescribe!=null){
            throw  new CustomException("已提交处方申请，正在开方...");
        }
        FsStoreOrderItem orderItemMap=new FsStoreOrderItem();
        orderItemMap.setOrderId(order.getId());
        orderItemMap.setIsPrescribe(1);
        List<FsStoreOrderItem> items= orderItemService.selectFsStoreOrderItemList(orderItemMap);
        String rpId=OrderUtils.getOrderNo();
        FsPatient patient=patientService.selectFsPatientById(param.getPatientId());
        FsUser user=userService.selectFsUserById(userId);
        PrescribeV2Param prescribeParam=new PrescribeV2Param();
        PrescribeV2 prescribe=new PrescribeV2();
        prescribe.setDrugType("01");
        prescribe.setOnlyId(rpId);
        prescribe.setDrugstoreName("零利润药房");
        prescribe.setPatientName(patient.getPatientName());
        prescribe.setPatientAge(DateUtils.getAge(patient.getBirthday()));
//        prescribe.setPatientTel(user.getPhone());
        prescribe.setPatientSex(patient.getGender());
        prescribe.setPatientAllergy(param.getIsAllergic()?1:0);
        prescribe.setLiverUnusual(param.getIsLiver()?1:0);
        prescribe.setRenalUnusual(param.getIsRenal()?1:0);
        prescribe.setLactationFlag(param.getIsLactation()?1:0);
        prescribe.setChiefComplaint(param.getChiefComplaint());
        prescribe.setNowIllness(param.getNowIllness());
        prescribe.setHistoryIllness(param.getHistoryIllness());
        if(StringUtils.isNotEmpty(param.getRecordPic())){
            prescribe.setRecordPic(param.getRecordPic().split(","));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        prescribe.setCreateTime(sdf.format(now));
        prescribe.setPictureType("png");
//        prescribe.setLactationFlag("否");
        prescribe.setCallbackUrl(fsSysConfig.getCallbackUrl());

        List<DrugV2> drug_list=new ArrayList<>();
        for(FsStoreOrderItem item:items){
            FsStoreProduct product=productService.selectFsStoreProductById(item.getProductId());
            DrugV2 drug=new DrugV2();
            drug.setDrugCommonName(product.getPrescribeName());
            drug.setDrugSpecification(product.getPrescribeSpec());
            drug.setSaleAmount(item.getNum().toString());
            drug.setSaleUnit(product.getUnitName());
            drug.setApprovalNumber(product.getPrescribeCode());
            drug.setDrugCode(product.getProductId());
            drug_list.add(drug);
            prescribe.setDrugList(drug_list);
            prescribeParam.setData(prescribe);
        }
        R response=prescribeService.doPrescribeV2(prescribeParam);
        if(response.get("code").equals(200)){
            FsPrescribe fsPrescribe=new FsPrescribe();
            fsPrescribe.setRpId(rpId);
            fsPrescribe.setUserId(userId);
            fsPrescribe.setPatientId(patient.getPatientId());
            fsPrescribe.setPharmacyCode("00001");
            fsPrescribe.setPharmacyName("零利润药房");
            fsPrescribe.setStatus(0);
            fsPrescribe.setPrescribeType(1);
            fsPrescribe.setOrderId(order.getId());
            fsPrescribe.setCreateTime(new Date());
            fsPrescribe.setPatientGender(patient.getGender().toString());
            fsPrescribe.setPatientName(patient.getPatientName());
            fsPrescribe.setIsHistoryAllergic(param.getIsAllergic()?"是":"否");
            fsPrescribe.setLiverUnusual(param.getIsLiver()?"是":"否");
            fsPrescribe.setLactationFlag(param.getIsLactation()?"是":"否");
            fsPrescribe.setRenalUnusual(param.getIsRenal()?"是":"否");
            fsPrescribe.setChiefComplaint(param.getChiefComplaint());
            fsPrescribe.setNowIllness(param.getNowIllness());
            fsPrescribe.setHistoryIllness(param.getHistoryIllness());
            fsPrescribe.setRecordPic(param.getRecordPic());
            fsPrescribe.setPatientAge(String.valueOf( DateUtils.getAge(patient.getBirthday())));
            fsPrescribeMapper.insertFsPrescribe(fsPrescribe);

            FsStoreOrder orderMap=new FsStoreOrder();
            orderMap.setId(order.getId());
            orderMap.setPrescribeId(fsPrescribe.getPrescribeId());
            orderService.updateFsStoreOrder(orderMap);
            return R.ok("操作成功").put("order",order);

        }
        else{
            return R.error(response.get("msg").toString());
        }
    }

    @Override
    public FsPrescribe selectFsPrescribeByRpId(String rpId) {
        return fsPrescribeMapper.selectFsPrescribeByRpId(rpId);
    }

    @Override
    public List<FsPrescribeVO> selectFsPrescribeListQuery(FsPrescribeQueryParam param) {
        return fsPrescribeMapper.selectFsPrescribeListQuery(param);

    }

    @Override
    public List<FsPrescribeVO> selectFsPrescribeListVO(FsPrescribeVOParam fsPrescribe) {
        return fsPrescribeMapper.selectFsPrescribeListVO(fsPrescribe);
    }

    @Override
    public FsPrescribe selectFsPrescribeByOrderId(Long id) {
        return fsPrescribeMapper.selectFsPrescribeByOrderId(id);
    }
}
