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.Prescribe;
import com.fs.store.domain.*;
import com.fs.store.param.FsPrescribeParam;
import com.fs.store.param.FsPrescribeQueryParam;
import com.fs.store.param.FsPrescribeVOParam;
import com.fs.store.param.PrescribeParam;
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);
        PrescribeParam prescribeParam=new PrescribeParam();
        List<Prescribe> data=new ArrayList<>();
        Prescribe prescribe=new Prescribe();
        prescribe.setRp_type("01");
        prescribe.setRp_id(rpId);
        prescribe.setPharmacy_code("00001");
        prescribe.setPharmacy_name("默认门店");
        prescribe.setPatient_name(patient.getPatientName());
        prescribe.setPatient_age(DateUtils.getAge(patient.getBirthday()));
        prescribe.setPatient_tel(user.getPhone());
        prescribe.setPatient_gender(patient.getGender().toString());
        prescribe.setIs_history_allergic(param.getIsAllergic()?"是":"否");
        prescribe.setLiver_unusual(param.getIsLiver()?"是":"否");
        prescribe.setRenal_unusual(param.getIsRenal()?"是":"否");
        prescribe.setLactation_flag(param.getIsLactation()?"是":"否");
        prescribe.setChief_complaint(param.getChiefComplaint());
        prescribe.setNow_illness(param.getNowIllness());
        prescribe.setHistory_illness(param.getHistoryIllness());
        if(StringUtils.isNotEmpty(param.getRecordPic())){
            prescribe.setRecord_pic(param.getRecordPic().split(","));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        prescribe.setRp_create_time(sdf.format(now));
        prescribe.setRp_url_type("png");
        prescribe.setLactation_flag("否");
        prescribe.setCallback_url(fsSysConfig.getCallbackUrl());
        data.add(prescribe);

        List<Drug> drug_list=new ArrayList<>();
        for(FsStoreOrderItem item:items){
            FsStoreProduct product=productService.selectFsStoreProductById(item.getProductId());
            Drug drug=new Drug();
            drug.setDrug_common_name(product.getPrescribeName());
            drug.setDrug_specification(product.getPrescribeSpec());
            drug.setSale_amount(item.getNum().toString());
            drug.setSale_unit(product.getUnitName());
            drug.setApproval_number(product.getPrescribeCode());
            drug_list.add(drug);
            prescribe.setDrug_list(drug_list);
            prescribeParam.setData(data);
        }
        R response=prescribeService.doPrescribe(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);
    }
}
