package com.yihu.jw.complaint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.complaint.BaseComplaintDO;
import com.yihu.jw.entity.base.complaint.BaseComplaintDictDO;
import com.yihu.jw.entity.base.complaint.BaseComplaintDoctorDO;
import com.yihu.jw.entity.base.complaint.BaseComplaintOperateLogDO;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.enterprise.EnterpriseService;
import org.apache.commons.lang3.StringUtils;
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.util.*;

@Service
public class BaseComplaintService {
    @Autowired
    private BaseComplaintDictDao baseComplaintDictDao;
    @Autowired
    private BaseComplaintDoctorDao baseComplaintDoctorDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseComplaintDao baseComplaintDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;
    @Autowired
    private BaseComplaintOperateDao baseComplaintOperateDao;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Value("${wechat.id}")
    private String wxId;
    @Value("${wechat.flag}")
    private boolean flag;

    //修改新增
    public BaseComplaintDictDO createOrUpdateDict(String id, String name) {
        BaseComplaintDictDO baseComplaintDictDO = new BaseComplaintDictDO();
        if (StringUtils.isNoneBlank(id)) {
            baseComplaintDictDO = baseComplaintDictDao.findById(id);
            baseComplaintDictDO.setName(name);
            baseComplaintDictDO.setUpdateTime(new Date());
        } else {
            baseComplaintDictDO.setIsDel("1");
            baseComplaintDictDO.setName(name);
            baseComplaintDictDO.setCreateTime(new Date());
        }
        return baseComplaintDictDao.save(baseComplaintDictDO);
    }

    //删除
    public BaseComplaintDictDO deleteDict(String id) {
        BaseComplaintDictDO baseComplaintDictDO = baseComplaintDictDao.findById(id);
        if (null != baseComplaintDictDO) {
            baseComplaintDictDO.setIsDel("0");
            baseComplaintDictDO.setUpdateTime(new Date());
            baseComplaintDictDao.save(baseComplaintDictDO);
        }
        List<BaseComplaintDoctorDO> baseComplaintDoctorDOs = baseComplaintDoctorDao.findbyComplaintId(id);
        for (BaseComplaintDoctorDO baseComplaintDoctorDO:baseComplaintDoctorDOs){
            baseComplaintDoctorDO.setIsDel("0");
        }
        baseComplaintDoctorDao.save(baseComplaintDoctorDOs);

        return baseComplaintDictDO;
    }

    public BaseComplaintDictDO findOneDict(String id) {
        BaseComplaintDictDO baseComplaintDictDO = baseComplaintDictDao.findById(id);
        return baseComplaintDictDO;
    }

    //查询
    public List<BaseComplaintDictDO> findAll(String name) {
        List<BaseComplaintDictDO> list = new ArrayList<>();
        if (StringUtils.isNoneBlank(name)) {
            list = baseComplaintDictDao.findByName(name);
        } else {
            list = baseComplaintDictDao.findByAll();
        }
        return list;
    }

    //新增投诉管理医生
    @Transactional
    public void createOrUpdateComplainDoctor(String id, String complaintId, String doctorList) throws Exception {
        JSONArray jsonArray = JSON.parseArray(doctorList);
        for (int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String doctor = jsonObject.getString("doctor");
            String deptCode = jsonObject.getString("deptCode");
            String deptName = "";
            String doctorName = "";
            BaseComplaintDoctorDO preDoctor= baseComplaintDoctorDao.findbyDoctorAndDel(doctor);
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
            List<BaseDoctorRoleDO> baseDoctorRoleDOs = baseDoctorRoleDao.findByDoctorCode(doctor);
            if (baseDoctorRoleDOs==null||baseDoctorRoleDOs.size()==0){
                BaseDoctorRoleDO baseDoctorRoleDO = new BaseDoctorRoleDO();
                baseDoctorRoleDO.setDoctorCode(doctor);
                baseDoctorRoleDO.setRoleCode("specialist");
                baseDoctorRoleDao.save(baseDoctorRoleDO);
            }else if (baseDoctorRoleDOs!=null){
                Boolean addRoleFlag=true;//是否为对应医生添加专科医生角色表示 true即为添加
                for (BaseDoctorRoleDO baseDoctorRoleDO :baseDoctorRoleDOs){
                    if (baseDoctorRoleDO.getRoleCode().equalsIgnoreCase("specialist")){
                        addRoleFlag=false;
                    }
                }
                if(addRoleFlag){
                    BaseDoctorRoleDO baseDoctorRoleDO = new BaseDoctorRoleDO();
                    baseDoctorRoleDO.setDoctorCode(doctor);
                    baseDoctorRoleDO.setRoleCode("specialist");
                    baseDoctorRoleDao.save(baseDoctorRoleDO);
                }
            }
            if (null != baseDoctorDO) {
                doctorName = baseDoctorDO.getName();
            }
            if (preDoctor!=null){
                throw new Exception("医生"+doctorName+"已有负责的投诉类型");
            }
            List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDeptCodeDoctorCode(deptCode, doctor);
            if (baseDoctorHospitalDO != null && baseDoctorHospitalDO.size() > 0) {
                deptName = baseDoctorHospitalDO.get(0).getDeptName();
            }
            if (StringUtils.isNoneBlank(id)) {
                BaseComplaintDoctorDO baseComplaintDoctorDO = new BaseComplaintDoctorDO();
                baseComplaintDoctorDO.setDept(deptCode);
                baseComplaintDoctorDO.setDeptName(deptName);
                baseComplaintDoctorDO.setComplaintId(id);
                baseComplaintDoctorDO.setDoctor(doctor);
                baseComplaintDoctorDO.setDoctorName(doctorName);
                baseComplaintDoctorDO.setIsDel("1");
                baseComplaintDoctorDO.setCreateTime(new Date());
                baseComplaintDoctorDao.save(baseComplaintDoctorDO);
            }
        }
    }
    //删除管理医生
    public BaseComplaintDoctorDO deleteDoctorComplain(String id) {
        BaseComplaintDoctorDO baseComplaintDoctorDO = baseComplaintDoctorDao.findByDelAndId(id);
        if (null != baseComplaintDoctorDO) {
            baseComplaintDoctorDO.setIsDel("0");
            baseComplaintDoctorDO.setUpdateTime(new Date());
            baseComplaintDoctorDao.save(baseComplaintDoctorDO);
        }
        return baseComplaintDoctorDO;
    }

    public MixEnvelop findComplaintDoctor(String doctor,String doctorName, String deptName, String complaintType, Integer page, Integer pageSize) {
        String sql = "select t.id as \"id\"," +
                " t.complaint_id as \"complaintId\"," +
                " t.doctor as \"doctor\"," +
                " t.doctor_name as \"doctorName\"," +
                " t.dept as \"dept\"," +
                " t.dept_name as \"deptName\"," +
                " t.is_del as \"isDel\"," +
                " t.create_time as \"createTime\"," +
                " t.update_time as \"updateTime\"," +
                " d.photo as \"photo\"," +
                " b.name as \"name\" " +
                " from base_complaint_doctor t left join base_complaint_dict b" +
                " on t.complaint_id=b.id " +
                " left join base_doctor d on t.doctor=d.id where t.is_del='1'";
        if (StringUtils.isNoneBlank(doctorName)) {
            sql += " and t.doctor_name like '%" + doctorName + "%'";
        }
        if (StringUtils.isNoneBlank(deptName)) {
            sql += " and t.dept_name like '%" + deptName + "%'";
        }
        if (StringUtils.isNoneBlank(complaintType)) {
            sql += " and t.complaint_id = '" + complaintType + "'";
        }
        if (StringUtils.isNoneBlank(doctor)) {
            sql += " and t.doctor = '" + doctor + "'";
        }
        sql += "order by t.create_time desc";
        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.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setDetailModelList(list);
        return mixEnvelop;
    }

    public BaseComplaintDoctorDO findOneDoctorComplain(String id) {
        BaseComplaintDoctorDO baseComplaintDoctorDO = baseComplaintDoctorDao.findByDelAndId(id);
        return baseComplaintDoctorDO;
    }
    /*
     * 患者举报接口
     * */
    public BaseComplaintDO patiemtComplaint(String json) throws Exception{
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO= wlyyHospitalSysDictDao.findById("complaintOpenControl");
        if (wlyyHospitalSysDictDO!=null){
            if (!"1".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                throw new Exception("投诉通道已关闭");
            }
        }else {
            throw new Exception("投诉通道已关闭");
        }
        BaseComplaintDO baseComplaintDO =objectMapper.readValue(json,BaseComplaintDO.class);
        BaseComplaintDictDO baseComplaintDictDO = baseComplaintDictDao.findById(baseComplaintDO.getComplaintId());
        if (baseComplaintDictDO!=null){
            baseComplaintDO.setComplaintName(baseComplaintDictDO.getName());
        }
        if (StringUtils.isNoneBlank(baseComplaintDO.getVisitDept())){
            DictHospitalDeptDO dictHospitalDeptDO=dictHospitalDeptDao.findByCode(baseComplaintDO.getVisitDept());
            if (dictHospitalDeptDO!=null){
                baseComplaintDO.setVisitDeptName(dictHospitalDeptDO.getName());
            }
        }
        /*if(StringUtils.isNoneBlank(baseComplaintDO.getPatient())){
            BasePatientDO basePatientDO= basePatientDao.findById(baseComplaintDO.getPatient());
            if (basePatientDO!=null){
                basePatientDO.setIdcardFront(baseComplaintDO.getIdcardFront());
                basePatientDO.setIdcardBack(baseComplaintDO.getIdcardBack());
                basePatientDao.save(basePatientDO);
            }

        }*/
        baseComplaintDO.setIsDel("1");
        baseComplaintDO.setStatus("0");
        baseComplaintDO.setCreateTime(new Date());
        baseComplaintDO.setDefaultdoctor("defalutDoctor");
        baseComplaintDO=  baseComplaintDao.save(baseComplaintDO);
        BaseComplaintOperateLogDO baseComplaintOperateLogDO = new BaseComplaintOperateLogDO();
        baseComplaintOperateLogDO.setOperateFrom(baseComplaintDO.getPatient());
        baseComplaintOperateLogDO.setStatus("0");
        baseComplaintOperateLogDO.setOperateType("投诉提交");
        baseComplaintOperateLogDO.setRelationCode(baseComplaintDO.getId());
        baseComplaintOperateLogDO.setCreateTime(new Date());
        baseComplaintOperateDao.save(baseComplaintOperateLogDO);
        try {
            List<BaseComplaintDoctorDO> doctorList=baseComplaintDoctorDao.findbyComplaintId(baseComplaintDO.getComplaintId());
            for (BaseComplaintDoctorDO baseComplaintDoctorDO:doctorList){
                String url="https://hlwyy.xmzsh.com/hlwyy/ims-app-web/#/complaint/detail?id="+baseComplaintDO.getId();
                enterpriseService.sendTWMesByDoctor("zsyy",baseComplaintDoctorDO.getDoctor(),"投诉反馈","您收到一条投诉反馈，点击查看。",url);
            }
        }catch (Exception e){

        }
       return baseComplaintDao.save(baseComplaintDO);
    }
    /*
     * 医生转交
     * */
    public BaseComplaintDO passTo(String id,String complaintId,String doctor,String operator,String reason){
        BaseComplaintDO baseComplaintDO = baseComplaintDao.findOne(id);
        BaseComplaintOperateLogDO baseComplaintOperateLogDO = new BaseComplaintOperateLogDO();
        String doctorName="";
        String complaitTypeName="";
        if (null!=baseComplaintDO){
            baseComplaintOperateLogDO.setOperateFrom(operator);
            baseComplaintOperateLogDO.setReason(reason);
            baseComplaintOperateLogDO.setOperateTo(doctor);
            baseComplaintOperateLogDO.setComplaintTo(complaintId);
            baseComplaintOperateLogDO.setComplaintFrom(baseComplaintDO.getComplaintId());
            baseComplaintOperateLogDO.setStatus("3");
            baseComplaintOperateLogDO.setOperateType("转交");
            baseComplaintOperateLogDO.setRelationCode(id);
            baseComplaintOperateLogDO.setCreateTime(new Date());
            baseComplaintOperateDao.save(baseComplaintOperateLogDO);
            /*BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
            if (null != baseDoctorDO) {
                doctorName=baseDoctorDO.getName();
                baseComplaintDO.setAcceptorName(doctorName);
            }
            baseComplaintDO.setAcceptor(doctor);*/
            if ("1".equalsIgnoreCase(baseComplaintDO.getStatus())){
                baseComplaintDO.setStatus("0");
            }
            baseComplaintDO.setDefaultdoctor(doctor);
            baseComplaintDO.setComplaintId(complaintId);
            baseComplaintDO.setPassto(doctor);
            BaseComplaintDictDO baseComplaintDictDO = baseComplaintDictDao.findById(complaintId);
            if (baseComplaintDictDO!=null){
                complaitTypeName=baseComplaintDictDO.getName();
                baseComplaintDO.setComplaintName(complaitTypeName);
            }
            baseComplaintDO= baseComplaintDao.save(baseComplaintDO);
            try {
                /*List<BaseComplaintDoctorDO> doctorList=baseComplaintDoctorDao.findbyComplaintId(baseComplaintDO.getComplaintId());
                for (BaseComplaintDoctorDO baseComplaintDoctorDO:doctorList)*/
                String url="https://hlwyy.xmzsh.com/hlwyy/ims-app-web/#/complaint/detail?id="+baseComplaintDO.getId();
                enterpriseService.sendTWMesByDoctor("zsyy",doctor,"投诉反馈","您收到一条投诉反馈，点击查看。",url);

            }catch (Exception e){

            }
            return baseComplaintDO;
        }
        return null;
    }
    //接受投诉
    public BaseComplaintDO doctorAccept(String id,String doctor) throws Exception{
        BaseComplaintDO baseComplaintDO = baseComplaintDao.findOne(id);
        if (baseComplaintDO!=null){
            baseComplaintDO.setStatus("1");
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
            if (null != baseDoctorDO) {
                baseComplaintDO.setAcceptorName(baseDoctorDO.getName());
            }
            baseComplaintDO.setAcceptor(doctor);
            baseComplaintDO.setDefaultdoctor(doctor);
            baseComplaintDO.setAcceptTime(new Date());
            baseComplaintDao.save(baseComplaintDO);
            BaseComplaintOperateLogDO baseComplaintOperateLogDO = new BaseComplaintOperateLogDO();
            baseComplaintOperateLogDO.setOperateFrom(doctor);
            baseComplaintOperateLogDO.setStatus("1");
            baseComplaintOperateLogDO.setOperateType("接受");
            baseComplaintOperateLogDO.setRelationCode(id);
            baseComplaintOperateLogDO.setCreateTime(new Date());
            baseComplaintOperateDao.save(baseComplaintOperateLogDO);
        }/*else if ("1".equalsIgnoreCase(baseComplaintDO.getStatus())){
            throw new Exception("该工单已被接受");
        }else {
            throw new Exception("该工单已被处理完成");
        }*/
        return baseComplaintDO;
    }
    //反馈投诉
    public BaseComplaintDO dealComplaint(String id,String operator,String content,String imgUrl ,String deptCode) throws  Exception{
        BaseComplaintDO baseComplaintDO = baseComplaintDao.findOne(id);
        if (baseComplaintDO!=null){
            baseComplaintDO.setDealTime(new Date());
            baseComplaintDO.setFeedBack(content);
            baseComplaintDO.setFeedImg(imgUrl);
            baseComplaintDO.setOperator(operator);
            baseComplaintDO.setDefaultdoctor(operator);
            baseComplaintDO.setStatus("2");
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(operator);
            if (null != baseDoctorDO) {
                baseComplaintDO.setOperatorName(baseDoctorDO.getName());
            }
            baseComplaintDO.setOperatorDept(deptCode);
            List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDeptCodeDoctorCode(deptCode, operator);
            if (baseDoctorHospitalDO != null && baseDoctorHospitalDO.size() > 0) {
                baseComplaintDO.setOperatorDeptName(baseDoctorHospitalDO.get(0).getDeptName());
            }
            baseComplaintDao.save(baseComplaintDO);
            BaseComplaintOperateLogDO baseComplaintOperateLogDO = new BaseComplaintOperateLogDO();
            baseComplaintOperateLogDO.setOperateFrom(operator);
            baseComplaintOperateLogDO.setStatus("2");
            baseComplaintOperateLogDO.setOperateType("反馈");
            baseComplaintOperateLogDO.setRelationCode(id);
            baseComplaintOperateLogDO.setCreateTime(new Date());
            baseComplaintOperateDao.save(baseComplaintOperateLogDO);
        }/*else if ("2".equalsIgnoreCase(baseComplaintDO.getStatus())){
            throw new Exception("该工单已被处理完成");
        }else if ("0".equalsIgnoreCase(baseComplaintDO.getStatus())){
            throw new Exception("该工单未被接收");
        }*/
        return baseComplaintDO;
    }

    //查询投诉列表
    public MixEnvelop findComplaintList(String role,String doctor,String status,String patientName,String patientId,String keyWord,String complaintId,
                                  String startTime,String endTime,Integer page ,Integer pageSize){
        MixEnvelop mixEnvelop = new MixEnvelop();
        Boolean queryAll=false;
        if ("admin".equalsIgnoreCase(role)){
            queryAll=true;
        }
        String sql="select DISTINCT t.id as \"id\"," +
                " t.complaint_id as \"complaintId\"," +
                " t.complaint_name as \"complaintName\"," +
                " t.complaint_content as \"complaintContent\"," +
                " t.visit_type as \"visitType\"," +
                " case  t.visit_type when '1' then '门诊' else '住院' end  as \"visitTypeName\"," +
                " t.visit_time as \"visitTime\"," +
                " t.visit_dept as \"visitDept\"," +
                " t.visit_dept_name as \"visitDeptName\"," +
                " t.adm_no as \"admNo\"," +
                " t.patient as \"patient\"," +
                " t.patient_name as \"patientName\"," +
                " t.patient_idcard as \"patientIdcard\"," +
                " t.idcard_front as \"idcardFront\"," +
                " t.idcard_back as \"idcardBack\"," +
                " t.img_url as \"imgUrl\"," +
                " t.is_del as \"isDel\"," +
                " t.status as \"status\"," +
                " t.create_time as \"createTime\"," +
                " t.accept_time as \"acceptTime\"," +
                " t.deal_time as \"dealTime\"," +
                " t.operator_dept as \"operatorDept\"," +
                " t.operator_dept_name as \"operatorDeptName\"," +
                " t.operator as \"operator\"," +
                " t.operator_name as \"operatorName\"," +
                " t.feed_back as \"feedBack\"," +
                " t.feed_img as \"feedImg\"," +
                " t.acceptor as \"acceptor\"," +
                " t.mobile as \"mobile\"," +
                " t.passto as \"passto\"," +
                " t.acceptor_name as \"acceptorName\"" +
                " from base_complaint t  " +
                " left join base_patient b on t.patient=b.id " ;
        sql+=" left join base_complaint_operate_log g on t.id=g.relation_code where t.is_del='1 '";
        if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
            sql+=" and  g.status='3' ";
        }/*else if (StringUtils.isNoneBlank(status)&&"1".equalsIgnoreCase(status)){
            sql+=" and  g.status='1' ";
        }
        else if (StringUtils.isNoneBlank(status)&&"2".equalsIgnoreCase(status)){
            sql+=" and  g.status='2' ";
        }*/
        if (!queryAll){
            BaseComplaintDoctorDO baseComplaintDoctorDO= baseComplaintDoctorDao.findbyDoctorAndDel(doctor);
            /*List<BaseComplaintOperateLogDO> logList =baseComplaintOperateDao.findbyOperateFrom(doctor);
            String types= "";
            if (logList!=null&&logList.size()>0){
                for (int i=0;i<logList.size();i++){
                    if (i==logList.size()-1){
                        types+=logList.get(i).getComplaintTo();
                    }else {
                        types+=logList.get(i).getComplaintTo()+",";
                    }
                }
            }*/
            String complaint="";
            if (baseComplaintDoctorDO!=null){
                if (baseComplaintDoctorDO.getComplaintId().equalsIgnoreCase("808080eb7a194099017a1943fa820004")){
                    complaint=baseComplaintDoctorDO.getComplaintId();
                }
            }
            //complaint=complaint+","+types;
            if (StringUtils.isNoneBlank(complaint)){
                if (!StringUtils.isNoneBlank(status)){
                    sql+=" and t.status !='-1'";
                    sql+=" and (t.defaultdoctor ='defalutDoctor' or t.defaultdoctor='"+doctor+"')";
                }
                if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
                    sql+=" and g.operate_from='"+doctor+"'";
                }else {
                    sql+=" and t.complaint_id='"+complaint+"'";
                }
                if (!StringUtils.isNoneBlank(status)){
                    sql+=" or (g.operate_from='"+doctor+"'  and g.status='3')";
                }
                if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
                    sql+=" and g.operate_from='"+doctor+"'";
                }else if (StringUtils.isNoneBlank(status)&&"0".equalsIgnoreCase(status)){
                    sql+=" and t.status='0' and (t.passto='"+doctor+"' or t.passto is null )";
                } else if (StringUtils.isNoneBlank(status)&&"1".equalsIgnoreCase(status)){
                    sql+="  and t.status='1' and t.acceptor='"+doctor+"' ";
                } else if (StringUtils.isNoneBlank(status)&&"2".equalsIgnoreCase(status)){
                    sql+=" and t.status='2' and t.operator='"+doctor+"' ";
                }

                //sql+=" and t.complaint_id in ('"+complaint.replace(",","','")+"')";
            }else {
                if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
                    sql+=" and g.operate_from='"+doctor+"'";
                }else if (StringUtils.isNoneBlank(status)&&"0".equalsIgnoreCase(status)){
                    sql+=" and t.status='0' and t.passto='"+doctor+"'";
                } else if (StringUtils.isNoneBlank(status)&&"1".equalsIgnoreCase(status)){
                    sql+="  and t.status='1' and t.acceptor='"+doctor+"' ";
                } else if (StringUtils.isNoneBlank(status)&&"2".equalsIgnoreCase(status)){
                    sql+=" and t.status='2' and t.operator='"+doctor+"' ";
                } else {
                    sql+=" and t.id IN (select col.relation_code from base_complaint_operate_log col where col.operate_to = '"+doctor+"'  )";
                }
            }
            //complaint=complaint+","+types;

        }else {
            if (StringUtils.isNoneBlank(complaintId)){
                //sql+=" and t.complaint_id in ('"+complaint.replace(",","','")+"')";
                sql+=" and t.complaint_id='"+complaintId+"'";
            }
            if (StringUtils.isNoneBlank(status)){
                sql+=" and t.status ='"+status+"'";
            }
        }

        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and t.patient_name like '%"+patientName+"%'";
        }
        if (StringUtils.isNoneBlank(patientId)){
            sql+=" and t.patient ='"+patientId+"'";
        }
        if (StringUtils.isNoneBlank(keyWord)){
            sql+=" and (t.patient_idcard like '%"+keyWord+"%' or t.patient_name like '%"+keyWord+"%')";
        }
        if (StringUtils.isNotBlank(startTime)){
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    sql+=" and t.create_time > '"+startTime+"'";
                }else {
                    sql+=" and t.create_time > to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time > '"+startTime+"'";
            }
        }
        if (StringUtils.isNotBlank(endTime)){
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    sql+="  and t.create_time<='" + endTime + "'";
                }else {
                    sql+="  and t.create_time<= to_date('" + endTime + "','yyyy-mm-dd hh24:mi:ss')";
                }
            }else{
                sql+="  and t.create_time<='" + endTime + "'";
            }
        }
        sql+=" order by t.create_time desc ";
        System.out.println("sql"+sql);
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        String sqlcount = "SELECT COUNT(1) AS \"total\" FROM ("+sql+") q";
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlcount);
        if(total!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        mixEnvelop.setTotalCount(count.intValue());
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        return mixEnvelop;
    }
    public BaseComplaintDO  findOnePaitentComplaint(String id){
        BaseComplaintDO baseComplaintDO = baseComplaintDao.findOne(id);
        BasePatientDO basePatientDO=basePatientDao.findById(baseComplaintDO.getPatient());
        if (null!=basePatientDO){
            baseComplaintDO.setMobile(basePatientDO.getMobile());
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO =wlyyHospitalSysDictDao.findById("latestFeedBackTime");
        Integer timeOut=15;
        if (wlyyHospitalSysDictDO!=null){
            timeOut =Integer.parseInt(wlyyHospitalSysDictDO.getDictValue());
        }
        long latestDate=baseComplaintDO.getCreateTime().getTime()+timeOut*24*60*60*1000;
        baseComplaintDO.setLatestFeedTime( (new Date(latestDate)));
        baseComplaintDO.setVisitTypeName(baseComplaintDO.getVisitType().equalsIgnoreCase("1")?"门诊":"住院");
        return baseComplaintDO;
    }





    //查询投诉列表
    public MixEnvelop findPatientComplaintList(String status,String patientName,String patientId,
                                        String startTime,String endTime,String complaintType,Integer page ,Integer pageSize){
        MixEnvelop mixEnvelop = new MixEnvelop();
        String sql="select t.id as \"id\"," +
                " t.complaint_id as \"complaintId\"," +
                " t.complaint_name as \"complaintName\"," +
                " t.complaint_content as \"complaintContent\"," +
                " t.visit_type as \"visitType\"," +
                " case  t.visit_type when '1' then '门诊' else '住院' end  as \"visitTypeName\"," +
                " t.visit_time as \"visitTime\"," +
                " t.visit_dept as \"visitDept\"," +
                " t.visit_dept_name as \"visitDeptName\"," +
                " t.adm_no as \"admNo\"," +
                " t.patient as \"patient\"," +
                " t.patient_name as \"patientName\"," +
                " t.patient_idcard as \"patientIdcard\"," +
                " t.idcard_front as \"idcardFront\"," +
                " t.idcard_back as \"idcardBack\"," +
                " t.img_url as \"imgUrl\"," +
                " t.is_del as \"isDel\"," +
                " t.status as \"status\"," +
                " t.create_time as \"createTime\"," +
                " t.accept_time as \"acceptTime\"," +
                " t.deal_time as \"dealTime\"," +
                " t.operator_dept as \"operatorDept\"," +
                " t.operator_dept_name as \"operatorDeptName\"," +
                " t.operator as \"operator\"," +
                " t.operator_name as \"operatorName\"," +
                " t.feed_back as \"feedBack\"," +
                " t.feed_img as \"feedImg\"," +
                " t.acceptor as \"acceptor\"," +
                " t.mobile as \"mobile\"," +
                " t.acceptor_name as \"acceptorName\"" +
                " from base_complaint t " +
                " left join base_patient b on t.patient=b.id" +
                " where t.is_del='1'";
        if (StringUtils.isNoneBlank(status)){
            sql+=" and t.status ='"+status+"'";
        }
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and t.patient_name like '%"+patientName+"%'";
        }
        if (StringUtils.isNoneBlank(patientId)){
            sql+=" and t.patient ='"+patientId+"'";
        }
        if (StringUtils.isNoneBlank(complaintType)){
            sql+=" and t.complaint_id ='"+complaintType+"'";
        }
        if (StringUtils.isNotBlank(startTime)){
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    sql+=" and t.create_time > '"+startTime+"'";
                }else {
                    sql+=" and t.create_time > to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time > '"+startTime+"'";
            }
        }
        if (StringUtils.isNotBlank(endTime)){
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    sql+="  and t.create_time<='" + endTime + "'";
                }else {
                    sql+="  and t.create_time<= to_date('" + endTime + "','yyyy-mm-dd hh24:mi:ss')";
                }
            }else{
                sql+="  and t.create_time<='" + endTime + "'";
            }
        }
        sql+=" order by t.create_time desc ";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        String sqlcount = "SELECT COUNT(1) AS \"total\" FROM ("+sql+") q";
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlcount);
        if(total!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        mixEnvelop.setTotalCount(count.intValue());
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        return mixEnvelop;
    }
    /*
    * 查询投诉数量*/
    public Map<String,Object> findComplaintCount(String doctor,String role){
        BaseComplaintDoctorDO baseComplaintDoctorDO=baseComplaintDoctorDao.findbyDoctorAndDel(doctor);
        Integer complaints=0;
        Integer recieve=0;
        Integer deal=0;
        Integer cacel=0;
        Integer passto=0;
        Integer total=0;
        if (baseComplaintDoctorDO!=null){
                Boolean queryAll=false;
                if ("admin".equalsIgnoreCase(role)){
                    queryAll=true;
                }
                if (!queryAll){
                    if ("808080eb7a194099017a1943fa820004".equalsIgnoreCase(baseComplaintDoctorDO.getComplaintId())) {
                        complaints = getCountByStatus(doctor,"0",role);
                        recieve = getCountByStatus(doctor,"1",role);
                        deal = getCountByStatus(doctor,"2",role);
                        passto = getCountByPassto(doctor);
                        total = getCountByStatus(doctor,"",role);
                    }else{
                        complaints=getCountByStatus(doctor,"0",role);
                        recieve=getCountByStatus(doctor,"1",role);
                        deal=getCountByStatus(doctor,"2",role);
                        passto=getCountByPassto(doctor);
                        total=getCountByStatus(doctor,"",role);
                    }
                    //cacel=baseComplaintDao.getCountByStatusAndComplaintId("-1",baseComplaintDoctorDO.getComplaintId());
                }else {
                    complaints=baseComplaintDao.getCountByStatus("0");
                    recieve=baseComplaintDao.getCountByStatus("1");
                    deal=baseComplaintDao.getCountByStatus("2");
                    cacel=baseComplaintDao.getCountByStatus("-1");
                    total = complaints+recieve+deal+cacel;
                }

        }
        Map map=new HashMap();
        map.put("complaints",complaints);
        map.put("recieve",recieve);
        map.put("deal",deal);
        map.put("passto",passto);
        map.put("cacel",cacel);
        map.put("total",total);
        return map;
    }
    public Integer getCountByPassto(String doctor){
        String sql ="select count(1) as \"total\" from (select  DISTINCT t.id   from base_complaint t left join base_complaint_operate_log b" +
                " on t.id=b.relation_code where t.is_del='1' and b.status='3'";
        if (StringUtils.isNoneBlank(doctor)){
            sql+=" and b.operate_from='"+doctor+"'";
        }
        sql+=") m";
        List<Map<String,Object>> listcount=hibenateUtils.createSQLQuery(sql);
        Integer count=0;
        if (listcount!=null&&listcount.size()>0){
            count=Integer.valueOf(listcount.get(0).get("total").toString());
        }
        return count;
    }
    public Integer getCountByStatus(String doctor,String status,String role){
        Boolean queryAll=false;
        if ("admin".equalsIgnoreCase(role)){
            queryAll=true;
        }
        String sql="select count(1)  as \"count\" from (select DISTINCT t.id  "+
                "  from base_complaint t  " +
                " left join base_patient b on t.patient=b.id " ;

        sql+=" left join base_complaint_operate_log g on t.id=g.relation_code where t.is_del='1' ";
        if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
            sql+="  and g.status='3' ";
        } /*else if (StringUtils.isNoneBlank(status)&&"1".equalsIgnoreCase(status)){
            sql+=" and  g.status='1' ";
        }
        else if (StringUtils.isNoneBlank(status)&&"2".equalsIgnoreCase(status)){
            sql+=" and  g.status='2' ";
        }*/
        if (!queryAll){
            BaseComplaintDoctorDO baseComplaintDoctorDO= baseComplaintDoctorDao.findbyDoctorAndDel(doctor);
            /*List<BaseComplaintOperateLogDO> logList =baseComplaintOperateDao.findbyOperateFrom(doctor);
            String types= "";
            if (logList!=null&&logList.size()>0){
                for (int i=0;i<logList.size();i++){
                    if (i==logList.size()-1){
                        types+=logList.get(i).getComplaintTo();
                    }else {
                        types+=logList.get(i).getComplaintTo()+",";
                    }
                }
            }*/
            String complaint="";
            if (baseComplaintDoctorDO!=null){
                if (baseComplaintDoctorDO.getComplaintId().equalsIgnoreCase("808080eb7a194099017a1943fa820004")){
                    complaint=baseComplaintDoctorDO.getComplaintId();
                }
            }
            //complaint=complaint+","+types;
            if (StringUtils.isNoneBlank(complaint)){
                if (!StringUtils.isNoneBlank(status)){
                    sql+=" and t.status !='-1'";
                    sql+=" and (t.defaultdoctor ='defalutDoctor' or t.defaultdoctor='"+doctor+"')";
                }
                if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
                    sql+=" and g.operate_from='"+doctor+"'";
                }else {
                    sql+=" and t.complaint_id='"+complaint+"'";
                }
               if (!StringUtils.isNoneBlank(status)){
                   sql+=" or (g.operate_from='"+doctor+"'  and g.status='3')";
                }
                if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
                    sql+=" and g.operate_from='"+doctor+"'";
                }else if (StringUtils.isNoneBlank(status)&&"0".equalsIgnoreCase(status)){
                    sql+=" and t.status='0' and (t.passto='"+doctor+"' or t.passto is null )";
                } else if (StringUtils.isNoneBlank(status)&&"1".equalsIgnoreCase(status)){
                    sql+="  and t.status='1' and t.acceptor='"+doctor+"' ";
                } else if (StringUtils.isNoneBlank(status)&&"2".equalsIgnoreCase(status)){
                    sql+=" and t.status='2' and t.operator='"+doctor+"' ";
                }
                //sql+=" and t.complaint_id in ('"+complaint.replace(",","','")+"')";
            }else {
                if (StringUtils.isNoneBlank(status)&&"3".equalsIgnoreCase(status)){
                    sql+=" and g.operate_from='"+doctor+"'";
                }else if (StringUtils.isNoneBlank(status)&&"0".equalsIgnoreCase(status)){
                    sql+=" and t.status='0' and t.passto='"+doctor+"'";
                } else if (StringUtils.isNoneBlank(status)&&"1".equalsIgnoreCase(status)){
                    sql+="  and t.status='1' and t.acceptor='"+doctor+"' ";
                } else if (StringUtils.isNoneBlank(status)&&"2".equalsIgnoreCase(status)){
                    sql+=" and t.status='2' and t.operator='"+doctor+"' ";
                } else {
                    sql+=" and t.id IN (select col.relation_code from base_complaint_operate_log col where col.operate_to = '"+doctor+"'  )";
                }
            }
            if (!StringUtils.isNoneBlank(status)){
                sql+=" and t.status !='-1'";
            }
            //complaint=complaint+","+types;

        }
        System.out.println("sql"+sql);
        Integer count = 0;
        sql+=")g";
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sql);
        if(total!=null&&total.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = Integer.valueOf(total.get(0).get("count").toString());
        }
        return count;
    }

    /*
     * 查询投诉数量*/
    public Map<String,Object> findComplaintCountPatient(String patient){
        Integer complaints=0;
        Integer recieve=0;
        Integer deal=0;
        Integer cacel=0;
        complaints=baseComplaintDao.getCountByStatusByPatient("0",patient);
        recieve=baseComplaintDao.getCountByStatusByPatient("1",patient);
        deal=baseComplaintDao.getCountByStatusByPatient("2",patient);
        cacel=baseComplaintDao.getCountByStatusByPatient("-1",patient);
        Integer total = complaints+recieve+deal+cacel;
        Map map=new HashMap();
        map.put("complaints",complaints);
        map.put("recieve",recieve);
        map.put("deal",deal);
        map.put("cacel",cacel);
        map.put("total",total);
        return map;
    }
    public BaseComplaintDO  cancelPaitentComplaint(String id,String patient) throws  Exception{
        BaseComplaintDO baseComplaintDO = baseComplaintDao.findOne(id);
       if (baseComplaintDO!=null){
           if ("0".equalsIgnoreCase(baseComplaintDO.getStatus())){
               baseComplaintDO.setStatus("-1");
               baseComplaintDO=baseComplaintDao.save(baseComplaintDO);
               BaseComplaintOperateLogDO baseComplaintOperateLogDO = new BaseComplaintOperateLogDO();
               baseComplaintOperateLogDO.setOperateFrom(patient);
               baseComplaintOperateLogDO.setStatus("-1");
               baseComplaintOperateLogDO.setOperateType("居民撤销投诉");
               baseComplaintOperateLogDO.setRelationCode(baseComplaintDO.getId());
               baseComplaintOperateLogDO.setCreateTime(new Date());
               baseComplaintOperateDao.save(baseComplaintOperateLogDO);
           }else {
               throw new Exception("不允许撤销");
           }

       }
       return baseComplaintDO;
    }
    public List<Map<String,Object>> findComplaintOperateLog(String complaintId){
        String sql ="select t.id as \"id\"," +
                " p.name as \"complaintNameFrom\" ," +
                " n.name as \"complaintNameto\", " +
                " t.operate_from as \"operateFrom\" ," +
                " t.reason as \"reason\" ," +
                " t.operate_to as \"operateTo\" ," +
                " t.cancel_by as \"cancelBy\", " +
                " t.operate_type as \"operateType\", " +
                " t.status as \"status\", " +
                " t.create_time as \"createTime\" ," +
                " t.relation_code as \"relationCode\" " +
                " from base_complaint_operate_log t left join base_complaint c" +
                " on t.relation_code=c.id" +
                " left join base_complaint_dict p on t.complaint_from= p.id" +
                " left join base_complaint_dict n on t.complaint_to=n.id where 1=1 " ;
        if (StringUtils.isNoneBlank(complaintId)){
            sql+=" and t.relation_code='"+complaintId+"'";
        }
        sql+=" order by t.create_time desc";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        List<WlyyHospitalSysDictDO> typeList=wlyyHospitalSysDictDao.findByDictName("complaintStatus");
        for (Map<String,Object> map:list){
            if (map.get("operateFrom")!=null){
                if (map.get("status")!=null){
                    for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:typeList){
                        if (map.get("status").toString().equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                            map.put("operateType",wlyyHospitalSysDictDO.getDictValue());
                        }
                    }
                    if ("0".equalsIgnoreCase(map.get("status").toString())||"-1".equalsIgnoreCase(map.get("status").toString())){
                        BasePatientDO basePatientDO = basePatientDao.findById(map.get("operateFrom").toString());
                        if (basePatientDO!=null){
                            map.put("operateFromName",basePatientDO.getName());
                        }
                    }else {
                        BaseDoctorDO baseDoctorDO= baseDoctorDao.findById(map.get("operateFrom").toString());
                        if (baseDoctorDO!=null){
                            map.put("operateFromName",baseDoctorDO.getName());
                        }
                        List<BaseDoctorHospitalDO> baseDoctorHospitalDO= baseDoctorHospitalDao.findByDoctorCode(map.get("operateFrom").toString());
                        if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
                            map.put("operateFromDeptName",baseDoctorHospitalDO.get(0).getDeptName());
                        }
                    }
                }
            }
            if (map.get("operateTo")!=null){
                BaseDoctorDO baseDoctorDO= baseDoctorDao.findById(map.get("operateTo").toString());
                if (baseDoctorDO!=null){
                    map.put("operateToName",baseDoctorDO.getName());
                }
                List<BaseDoctorHospitalDO> baseDoctorHospitalDO= baseDoctorHospitalDao.findByDoctorCode(map.get("operateTo").toString());
                if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
                    map.put("operateToDeptName",baseDoctorHospitalDO.get(0).getDeptName());
                }
            }
        }

    return list;
    }
}


