package com.yihu.jw.base.service.device;

import com.yihu.jw.base.dao.device.PatientDeviceDao;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.restmodel.iot.device.WlyyPatientDeviceVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Bing on 2021/9/22.
 */
@Service
public class WlyyPatientDeviceService extends BaseJpaService<DevicePatientDevice, PatientDeviceDao> {

    @Autowired
    private
    PatientDeviceDao patientDeviceDao;

    public void delPatientDevice(String id){
        DevicePatientDevice patientDevice = patientDeviceDao.findOne(Long.parseLong(id));
        String deviceSn = patientDevice.getDeviceSn();
        patientDeviceDao.delete(Long.parseLong(id));
        List<DevicePatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(deviceSn);
        String sql = "update device.wlyy_devices dd set dd.is_binding=? where dd.device_code=?";
        if (patientDeviceList.size()==0){
            jdbcTemplate.update(sql,new Object[]{0,deviceSn});
        }
        if (patientDeviceList.size()==1){
            jdbcTemplate.update(sql,new Object[]{1,deviceSn});
        }
        if (patientDeviceList.size()>1){
            jdbcTemplate.update(sql,new Object[]{2,deviceSn});
        }
    }

    public PageEnvelop<WlyyPatientDeviceVO> getUserDevice(String id,String userName,String userIdcard,String categoryCode,Integer page,Integer size){
        page = page>0?page-1:0;
        String sqlCondition = " from wlyy_patient_device pd " +
                " INNER JOIN base_patient p on pd.`user` = p.id INNER JOIN wlyy_devices wd on pd.device_sn = wd.device_code " +
                " where pd.del=0 ";
        if (StringUtils.isNotBlank(id)){
            sqlCondition+=" and pd.id='"+id+"' ";
        }
        if (StringUtils.isNotBlank(userName)){
            sqlCondition+=" and p.name like '%"+userName+"%' ";
        }
        if (StringUtils.isNotBlank(userIdcard)){
            sqlCondition+=" and pd.user_idcard like '%"+userIdcard+"%' ";
        }
        if (StringUtils.isNotBlank(categoryCode)){
            sqlCondition+=" and pd.category_code = '"+categoryCode+"' ";
        }
        String sqlCount = "select count(pd.id) " + sqlCondition;
        Long count = jdbcTemplate.queryForObject(sqlCount,Long.class);
        String sql = "select pd.*,p.name user_name,wd.device_model,wd.manufacturer " + sqlCondition +" limit "+page*size+","+size ;
        List<WlyyPatientDeviceVO> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(WlyyPatientDeviceVO.class));

        return PageEnvelop.getSuccessListWithPage("查询成功",list,page, size,count);
    }
}
