package com.yihu.jw.hospital.prescription.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.hospital.consult.dao.BaseAdviceTreatmentDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.service.BaseOperateLogService;
import com.yihu.jw.hospital.prescription.dao.*;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Trick on 2019/9/26.
 */
@Service
@Transactional
public class InspectionService extends BaseJpaService<WlyyInspectionDO, WlyyInspectionDao> {
    private static final Logger logger = LoggerFactory.getLogger(InspectionService.class);
    @Value("${demo.flag}")
    private boolean demoFlag;
    @Autowired
    private InspectionPartsDictDao inspectionPartsDictDao;
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseOperateLogService baseOperateLogService;
    @Autowired
    private BaseAdviceTreatmentDao baseAdviceTreatmentDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OutpatientDao outpatientDao;

    public List<WlyyInspectionPartsDictDO> findByPartsCode(String parentCode) {
        return inspectionPartsDictDao.findByParentCode(parentCode);
    }

    public List<WlyyHospitalSysDictDO> findDictByName(String hospital, String name) {
        return hospitalSysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital, name);
    }
    public MixEnvelop findInspectionByPatient(String patient,Integer page ,Integer pageSize){
        String sql = " select t.id as \"id\"," +
                " b.patient_name as \"patientName\"," +
                " b.consumer as \"consumer\"," +
                " b.consumer_name as \"consumerName\"," +
                " b.idcard as \"idcard\"," +
                " b.mobile as \"mobile\"," +
                " t.create_time as \"createTime\"," +
                " t.charge_amount as \"chargeAmount\"," +
                " t.quantity as \"quantity\"," +
                " t.code as \"code\"," +
                " t.name as \"name\"," +
                " t.dept as \"dept\"," +
                " t.dept_name as \"deptName\"," +
                " t.org_code as \"orgCode\"," +
                " t.org_name as \"orgName\"" +
                " from wlyy_inspection t " +
                " left join wlyy_outpatient b on t.outpatient_id = b.id" +
                " where t.del = 1 ";
        if (StringUtils.isNoneBlank(patient)){
            sql+= " and t.consumer '"+patient+"'";
        }else {
            sql+=" and t.consumer is null";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        return mixEnvelop;
    }
    public BaseAdviceTreatmentDO saveTreatment(String json,String adviceJson) throws Exception{
        BaseAdviceTreatmentDO baseAdviceTreatmentDO=objectMapper.readValue(adviceJson,BaseAdviceTreatmentDO.class);
        baseAdviceTreatmentDO.setDel(1);
        baseAdviceTreatmentDO.setCreateTime(new Date());
        baseAdviceTreatmentDO=baseAdviceTreatmentDao.save(baseAdviceTreatmentDO);
        if (StringUtils.isNotBlank(json)) {
            //药品
            List<WlyyPrescriptionInfoDO> infoDOs = (List<WlyyPrescriptionInfoDO>) com.alibaba.fastjson.JSONArray.parseArray(json, WlyyPrescriptionInfoDO.class);

            for (WlyyPrescriptionInfoDO info : infoDOs) {

                info.setDel(1);
                info.setPrescriptionId(baseAdviceTreatmentDO.getId());


            }
            //保存药品信息
            prescriptionInfoDao.save(infoDOs);
            logger.info("123");
            Double price = getInfoFee(infoDOs);
            logger.info("12312313213" + price);
            //计算药品费用
            baseAdviceTreatmentDO.setDrugFee(price);
            baseAdviceTreatmentDao.save(baseAdviceTreatmentDO);
        }
        WlyyOutpatientDO wlyyOutpatientDO=outpatientDao.findById(baseAdviceTreatmentDO.getRelationCode());
        if(wlyyOutpatientDO!=null){
            wlyyOutpatientDO.setIcd10Name(baseAdviceTreatmentDO.getDiagnosisName());
            wlyyOutpatientDO.setStatus("2");
            wlyyOutpatientDO.setAdvice(baseAdviceTreatmentDO.getTreatment());
            outpatientDao.save(wlyyOutpatientDO);
        }
        return baseAdviceTreatmentDO;
    }
    /**
     * 计算药品费用
     *
     * @param infoDOs
     * @return
     */
    public Double getInfoFee(List<WlyyPrescriptionInfoDO> infoDOs) {
        DecimalFormat df = new DecimalFormat("#.00");
        Double fee = 0D;
        if (infoDOs != null && infoDOs.size() > 0) {

            for (WlyyPrescriptionInfoDO info : infoDOs) {
                logger.error("getInfoFee===========Quantity:" + info.getQuantity());
                /*      Integer quantity = Integer.parseInt(info.getQuantity());*/
                logger.error("getInfoFee===========PackRetprice:" + info.getPackRetprice());
                /*   fee += info.getPackRetprice() * quantity;*/
                logger.error("getInfoFee===========:" + fee);
                BigDecimal total = new BigDecimal(0);
                BigDecimal quantity = new BigDecimal(info.getQuantity());
                BigDecimal price = new BigDecimal(info.getPackRetprice());
                total = total.add(quantity.multiply(price));
                Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                fee += f1;
            }
            logger.error("getInfoFee===========:" + fee);
        }
        return fee;
    }
}
