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

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.j2objc.annotations.AutoreleasePool;
import com.yihu.jw.entity.base.area.BaseDrugStoreDO;
import com.yihu.jw.entity.base.area.BaseDrugStoreTimeDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.message.BaseBannerDoctorDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.drugstore.dao.BaseDrugStoreDao;
import com.yihu.jw.hospital.drugstore.dao.BaseDrugStoreTimeDao;
import com.yihu.jw.hospital.message.dao.BaseBannerDoctorDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.CountDistance;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.provider.HibernateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Transactional
@Service
public class BaseDrugStoreService extends BaseJpaService<BaseDrugStoreDO, BaseDrugStoreDao> {
    @Autowired
    private BaseDrugStoreDao baseDrugStoreDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseDrugStoreTimeDao baseDrugStoreTimeDao;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;

   //根据经纬度计算距离通过代码
   public List<BaseDrugStoreDO> countDistanceListIncode(String latitude,String longitude,String drugStoreName,String hospitalName) throws ParseException {
       List<BaseDrugStoreDO> list = new ArrayList<>();
       if (StringUtils.isNotEmpty(drugStoreName)||StringUtils.isNotEmpty(hospitalName)){
           list = baseDrugStoreDao.findDrugByName(drugStoreName);
       }else {
           String filters="isDel=1;isUsed=1";
           list= this.search(filters);
       }
       List<BaseDrugStoreDO> resultlist = new ArrayList<>();
       CountDistance countDistance = new CountDistance();
       latitude=StringUtils.isEmpty(latitude)?"0":latitude;
       longitude=StringUtils.isEmpty(longitude)?"0":longitude;
        for (BaseDrugStoreDO baseDrugStoreDO:list){
            double storeLatitude = Double.parseDouble(baseDrugStoreDO.getLatitude());
            double storeLongitude = Double.parseDouble(baseDrugStoreDO.getLongitude());
            double distance = countDistance.getDistance(Double.parseDouble(latitude),Double.parseDouble(longitude),storeLatitude,storeLongitude);
            baseDrugStoreDO.setDistance(distance);
        }
        list.stream().sorted((x,y)->Double.compare(x.getDistance(),y.getDistance()));
        return list;
   }


    public BaseDrugStoreDO getById(String id,String latitude,String longitude){
        BaseDrugStoreDO baseDrugStoreDO = baseDrugStoreDao.findDrugByid(id);
        CountDistance countDistance = new CountDistance();
        latitude=StringUtils.isEmpty(latitude)?"0":latitude;
        longitude=StringUtils.isEmpty(longitude)?"0":longitude;
        double storeLatitude = Double.parseDouble(baseDrugStoreDO.getLatitude());
        double storeLongitude = Double.parseDouble(baseDrugStoreDO.getLongitude());
        double distance = countDistance.getDistance(Double.parseDouble(latitude),Double.parseDouble(longitude),storeLatitude,storeLongitude);
        baseDrugStoreDO.setDistance(distance);
        List<BaseDrugStoreTimeDO> list  = baseDrugStoreTimeDao.findByDrugStoreId(baseDrugStoreDO.getId());
        if (list!=null){
            baseDrugStoreDO.setBaseDrugStoreTimeDOlist(list);
        }
        if (StringUtils.isNoneBlank(baseDrugStoreDO.getOpenControl())){
            List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOList = wlyyHospitalSysDictDao.findByDictNameAndDictCode("drugStoreOpenControl",baseDrugStoreDO.getOpenControl());
            if (wlyyHospitalSysDictDOList!=null&&wlyyHospitalSysDictDOList.size()>0){
                baseDrugStoreDO.setOpenControlName(wlyyHospitalSysDictDOList.get(0).getDictValue());
            }
        }
        if (StringUtils.isNoneBlank(baseDrugStoreDO.getIsUsed())){
            List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOList = wlyyHospitalSysDictDao.findByDictNameAndDictCode("drugStoreStatus",baseDrugStoreDO.getIsUsed());
            if (wlyyHospitalSysDictDOList!=null&&wlyyHospitalSysDictDOList.size()>0){
                baseDrugStoreDO.setIsUsedName(wlyyHospitalSysDictDOList.get(0).getDictValue());
            }
        }
        return baseDrugStoreDO;
    }
    /*
    *
    */
    public BaseDrugStoreDO saveDrugStore(String jsonData,String timeDate) throws IOException {
        BaseDrugStoreDO baseDrugStoreDO = objectMapper.readValue(jsonData,BaseDrugStoreDO.class);
        if (StringUtils.isNoneBlank(baseDrugStoreDO.getId())){//修改
            if (StringUtils.isNoneBlank(timeDate)){
                //删除之前设置的药房开方时间
                baseDrugStoreTimeDao.deleteByDrugStoreId(baseDrugStoreDO.getId());
                JSONArray jsonArray = JSONArray.parseArray(timeDate);
                if (jsonArray!=null){
                    for (int i = 0;i<jsonArray.size();i++){
                        BaseDrugStoreTimeDO baseDrugStoreTimeDO = objectMapper.readValue(jsonArray.get(i).toString(), BaseDrugStoreTimeDO.class);
                        baseDrugStoreTimeDO.setDrugStoreId(baseDrugStoreDO.getId());
                        baseDrugStoreTimeDao.save(baseDrugStoreTimeDO);
                    }
                }

            }
            BaseDrugStoreDO baseDrugStorePre = baseDrugStoreDao.findOne(baseDrugStoreDO.getId());
            if (baseDrugStorePre!=null){
                BaseOrgDO baseOrgDO = baseOrgDao.findByCode(baseDrugStoreDO.getHospitalCode());
                if (baseOrgDO!=null){
                    baseDrugStorePre.setHospitalCode(baseDrugStoreDO.getHospitalCode());
                    baseDrugStorePre.setHospitalName(baseOrgDO.getName());
                }
                baseDrugStorePre.setOpenControlName(baseDrugStoreDO.getOpenControlName());
                baseDrugStorePre.setDrugStoreName(baseDrugStoreDO.getDrugStoreName());
                baseDrugStorePre.setDrugStoreCode(baseDrugStoreDO.getDrugStoreCode());
                baseDrugStorePre.setAddress(baseDrugStoreDO.getAddress());
                baseDrugStorePre.setRemark(baseDrugStoreDO.getRemark());
                baseDrugStorePre.setDrugImg(baseDrugStoreDO.getDrugImg());
                baseDrugStorePre.setOpenControl(baseDrugStoreDO.getOpenControl());
                baseDrugStorePre.setIsDel(1);
                baseDrugStorePre.setIsUsed(baseDrugStoreDO.getIsUsed());
                baseDrugStorePre.setLatitude(baseDrugStoreDO.getLatitude());
                baseDrugStorePre.setLongitude(baseDrugStoreDO.getLongitude());
                baseDrugStoreDO = baseDrugStoreDao.save(baseDrugStorePre);
            }
        }else {//新增
            baseDrugStoreDO.setIsDel(1);
            BaseOrgDO baseOrgDO = baseOrgDao.findByCode(baseDrugStoreDO.getHospitalCode());
            if (baseOrgDO!=null){
                baseDrugStoreDO.setHospitalName(baseOrgDO.getName());
            }
            baseDrugStoreDO = baseDrugStoreDao.save(baseDrugStoreDO);
            if (StringUtils.isNoneBlank(timeDate)){
                JSONArray jsonArray = JSONArray.parseArray(timeDate);
                if (jsonArray!=null){
                    for (int i = 0;i<jsonArray.size();i++){
                        BaseDrugStoreTimeDO baseDrugStoreTimeDO = objectMapper.readValue(jsonArray.get(i).toString(), BaseDrugStoreTimeDO.class);
                        baseDrugStoreTimeDO.setDrugStoreId(baseDrugStoreDO.getId());
                        baseDrugStoreTimeDao.save(baseDrugStoreTimeDO);
                    }
                }

            }
        }
        return baseDrugStoreDO;
    }
    //删除药房
    public void deleteDrugStore(String id,Integer isDel){
        BaseDrugStoreDO baseDrugStoreDO = baseDrugStoreDao.findOne(id);
        if (baseDrugStoreDO!=null){
            baseDrugStoreDO.setIsDel(isDel);
            baseDrugStoreDao.save(baseDrugStoreDO);
        }
    }
    //作废药房
    public void usedDrugStore(String id,String isUsed){
        BaseDrugStoreDO baseDrugStoreDO = baseDrugStoreDao.findOne(id);
        if (baseDrugStoreDO!=null){
            baseDrugStoreDO.setIsUsed(isUsed);
            baseDrugStoreDao.save(baseDrugStoreDO);
        }
    }
    public MixEnvelop findDrugStoreByConditions(String orgCode,String isUsed,String drugStoreName ,Integer page,Integer pageSize){
        MixEnvelop mixEnvelop = new MixEnvelop();
        String sql = "select b.id as \"id\"," +
                " b.drug_store_name as \"drugStoreName\"," +
                " b.address as \"address\"," +
                " b.drug_store_code as \"drugStoreCode\"," +
                " b.hospital_code as \"hospitalCode\"," +
                " b.hospital_name as \"hospitalName\"," +
                " b.remark as \"remark\"," +
                " b.open_control as \"openControl\"," +
                " b.is_used as \"isUsed\"," +
                " b.is_del as \"isDel\"" +
                "from base_drug_store b  where  is_del =1 ";
        if (StringUtils.isNoneBlank(orgCode)){
            sql+=" and b.hospital_code ='"+orgCode+"'";
        }
        if (StringUtils.isNoneBlank(drugStoreName)){
            sql+=" and b.drug_store_name like '%"+drugStoreName+"%'";
        }
        if (StringUtils.isNoneBlank(isUsed)){
            sql+=" and b.is_used ='"+isUsed+"' ";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
        for (Map<String,Object> map:list){
            List<BaseDrugStoreTimeDO> times = baseDrugStoreTimeDao.findByDrugStoreId(map.get("id").toString());
            map.put("openTime",times);
            if (map.get("openControl")!=null){
                List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOList = wlyyHospitalSysDictDao.findByDictNameAndDictCode("drugStoreOpenControl",map.get("openControl").toString());
                if (wlyyHospitalSysDictDOList!=null&&wlyyHospitalSysDictDOList.size()>0){
                    map.put("openControlName",wlyyHospitalSysDictDOList.get(0).getDictValue());
                }
            }
            if (map.get("isUsed")!=null){
                List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOList = wlyyHospitalSysDictDao.findByDictNameAndDictCode("drugStoreStatus",map.get("isUsed").toString());
                if (wlyyHospitalSysDictDOList!=null&&wlyyHospitalSysDictDOList.size()>0){
                    map.put("isUsedName",wlyyHospitalSysDictDOList.get(0).getDictValue());
                }
            }
        }
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
        return mixEnvelop;
    }
}
