package com.emr.service.approve;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.entity.Power_User;
import com.emr.entity.approve.Emr_Apply_Approve;
import com.emr.service.CommomService;
import com.emr.vo.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
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 javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/5/30 15:49
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/5/30 15:49
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
@Transactional
public class AppleApproveServiceImpl implements ApplyApproveService{
    @Autowired
    Emr_Apply_ApproveMapper applyApproveMapper;
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    @Override
    public void addEmrApplyApprove(Emr_Apply_Approve applyApprove, HttpServletRequest request) {
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        applyApprove.setApplyer(userName);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        applyApprove.setApplyTime(fmt.format(new Date()));
        applyApproveMapper.insert(applyApprove);
    }

    @Override
    public void updateEmrApplyApprove(Emr_Apply_Approve applyApprove) throws Exception{
        DateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd");
        //判断原来的是否是过期的，是则审核字段全部置空
        Emr_Apply_Approve oldApprove = applyApproveMapper.selectByPrimaryKey(applyApprove.getId());
        if(StringUtils.isNoneBlank(oldApprove.getEffeTime())){
            Date oldEffeTime = fmt1.parse(oldApprove.getEffeTime());
            if(oldEffeTime.getTime() < (System.currentTimeMillis() + 3600 * 1000)){
                applyApprove.setApprover("");
                applyApprove.setApproveTime("");
                applyApprove.setApproveState("");
                applyApprove.setApproveNotes("");
            }
        }
        // 驳回后再申请情况把申请时间重置为最新时间
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if("2".equals(applyApprove.getApproveState())){
            applyApprove.setApplyTime(fmt.format(new Date()));
            applyApprove.setApplyState("1");
        }
        applyApproveMapper.updateByPrimaryKeySelective(applyApprove);
    }

    @Override
    public void deleteByPrimaryKey(Integer id) {
        applyApproveMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Emr_Apply_Approve> selectNotSumbitPatientIdsByUser(String userName, String patientId,short type) {
        return applyApproveMapper.selectNotSumbitPatientIdsByUser(userName,patientId,type);
    }

    @Override
    public List<Emr_Apply_Approve> selectAllApproveByCreater(Emr_Apply_Approve applyApprove, String startTime1, String endTime1,String startTime2, String endTime2,HttpServletRequest request) {
        //查询收藏分类集合
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String applyer = user.getUserName();
        //如果登录者角色id=0，全查，如若不是，按用户id查
        Integer roleId = user.getRoleId();
        if(null != roleId && roleId == 0){
            //系统管理员全查
            return applyApproveMapper.selectAllApproveByCreater(null,applyApprove,startTime1,endTime1,startTime2,endTime2);
        }else if(null != roleId && roleId == -100){
            StringBuilder creaters = CommomService.creaters(request);
            return applyApproveMapper.selectAllApproveByCreater(creaters.toString(),applyApprove,startTime1,endTime1,startTime2,endTime2);
        }else if(null != roleId && roleId == -101){
            //TODO 可审批用户Id集合
            //审批人员角色id对应可审批申请者的id集合
            String applyers = "";
            return applyApproveMapper.selectAllApproveByCreater(applyers,applyApprove,startTime1,endTime1,startTime2,endTime2);
        }else{
            applyer = "'" + applyer + "'";
            return applyApproveMapper.selectAllApproveByCreater(applyer,applyApprove,startTime1,endTime1,startTime2,endTime2);
        }
    }

    @Override
    public List<Emr_Apply_Approve> selectAllApprove(Emr_Apply_Approve applyApprove, String startTime1, String endTime1,
                                                             String startTime2, String endTime2,HttpServletRequest request) throws Exception{
        StringBuilder creaters = new StringBuilder();
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        if(user.getRoleId() != 0 && user.getRoleId() != -100){
            String resultString = "";
            // 创建uri
            String url = POWER_URLHEAD+"/font/getUserList?userName="+user.getUserName();
            // 执行请求
            CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url));
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            JSONObject jsonObject = JSON.parseObject(resultString);
            String extend = jsonObject.getString("extend");
            JSONObject extendObject = JSONObject.parseObject(extend);
            String userList1 = extendObject.getString("userList");
            List<User> userList = (List<User>) JSON.parseArray(userList1,User.class);
            for (int i = 0; i < userList.size(); i++) {
                if(userList.get(i).getRoleId() != 0){
                    if(i != userList.size() - 1){
                        creaters.append("'").append(userList.get(i).getUserName()).append("',");
                    }else{
                        creaters.append("'").append(userList.get(i).getUserName()).append("'");
                    }
                }
            }
            if(",".equals(creaters.substring(creaters.length() - 1, creaters.length()))){
                creaters = new StringBuilder(creaters.substring(0,creaters.length()-1));
            }
        }else if(user.getRoleId() == -100){
            creaters = CommomService.creaters(request);
        }
        return applyApproveMapper.selectAllApprove(creaters.toString(),applyApprove,startTime1,endTime1,startTime2,endTime2);
    }

    @Override
    public int SimpleInsert(List<Emr_Apply_Approve> list) {
        return applyApproveMapper.SimpleInsert(list);
    }

    @Override
    public int SimpleUpdate(Emr_Apply_Approve record, String idsStr) {
        return applyApproveMapper.SimpleUpdate(record,idsStr);
    }

    @Override
    public void sendNotice(String applyType, int count) throws Exception{
        String url = POWER_URLHEAD + "/font/sendEmrRecordApproveNotice?applyType=" + applyType + "&count=" + count;
        // 执行请求
        HttpClients.createDefault().execute(new HttpGet(url));
    }

    @Override
    public List<String> expireTime(String currentTime,int effeDays) {
        return applyApproveMapper.expireTime(currentTime,effeDays);
    }
}
