package thyyxxk.webserver.service.surgicalmanagement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.surgicalmanagement.SurgeryArrangementDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.surgeryarrangement.QuerySurgeryParams;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.OpRecord;
import thyyxxk.webserver.service.redislike.RedisLikeService;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SurgeryArrangementService {
    private final SurgeryArrangementDao dao;
    private final RedisLikeService redis;
    private static final String[] OP_RECORD_COLUMNS = {"room_code", "op_datetime", "remark",
            "arrangement_executed", "urgent_clinic_flag", "preoperative_visit", "preoperative_preparation"};

    public SurgeryArrangementService(SurgeryArrangementDao dao, RedisLikeService redis) {
        this.dao = dao;
        this.redis = redis;
    }

    public ResultVo<Map<String, List<CodeName>>> getDicList() {
        Map<String, List<CodeName>> map = new HashMap<>();
        map.put("allRooms", dao.selectSurgeryRooms());
        map.put("allWards", dao.getAllSurgicalWard());
        map.put("surStaffs", dao.selectStaffsByDeptCode("1300000"));
        map.put("aneStaffs", dao.selectStaffsByDeptCode("1120000"));
        return ResultVoUtil.success(map);
    }

    public ResultVo<List<OpRecord>> selectSurgeryArrangements(QuerySurgeryParams param) {
        QueryWrapper<?> qw = new QueryWrapper<>();
        qw.ge("op_datetime", param.getStartTime());
        qw.le("op_datetime", param.getEndTime());
        if (param.getJzFlag()) {
            qw.eq("urgent_clinic_flag", "1");
        }
        if (!param.getStatus().equals("0")) {
            qw.eq("a.status", param.getStatus());
        }
        if (StringUtil.notBlank(param.getPatNo())) {
            qw.eq("a.inpatient_no", param.getPatNo());
        }
        if (StringUtil.notBlank(param.getWard())) {
            qw.eq("a.ward_code", param.getWard());
        }
        List<OpRecord> list = dao.selectSurgeryArrangements(qw);
        if (ListUtil.isBlank(list)) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST);
        }
        List<OpRecord> canceled = new ArrayList<>();
        list.forEach(item -> {
            item.setWardName(redis.getDeptName(item.getWardCode()));
            item.setApplyDocName(redis.getEmployeeName(item.getApplyDoc()));
            item.setDoctorZdName(redis.getEmployeeName(item.getDoctorZd()));
            item.setNurseXhName(redis.getEmployeeName(item.getNurseXh()));
            item.setNurseQxName(redis.getEmployeeName(item.getNurseQx()));
            item.setDoctorMzYsName(redis.getEmployeeName(item.getDoctorMzYs()));
            item.setDoctorMzHsName(redis.getEmployeeName(item.getDoctorMzHs()));
            if (item.getStatus().equals("d")) {
                canceled.add(item);
            }
        });
        list.removeIf(item -> item.getStatus().equals("d"));
        list.addAll(canceled);
        return ResultVoUtil.success(list);
    }

    public ResultVo<List<CodeName>> getSurgeryRooms() {
        return ResultVoUtil.success(dao.selectSurgeryRooms());
    }

    public ResultVo<String> updateSurgeryStatus(Integer recordId, String status) {
        if (hasArrangementPermission()) {
            dao.updateSurgeryStatus(recordId, status);
            return ResultVoUtil.success("操作成功。");
        }
        return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR, "操作失败，您没有安排手术的权限。");
    }

    private boolean isOpRecordColumn(String targetColumn) {
        for (String column : OP_RECORD_COLUMNS) {
            if (column.equals(targetColumn)) {
                return true;
            }
        }
        return false;
    }

    public ResultVo<String> updateArrangement(Integer recordId, String column, String value) {
        if (hasArrangementPermission()) {
            String table = isOpRecordColumn(column) ? "op_record" : "op_record_join";
            dao.updateArrangement(table, column, value, recordId);
            return ResultVoUtil.success();
        }
        return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR, "操作失败，您没有安排手术的权限。");
    }

    private boolean hasArrangementPermission() {
        if (TokenUtil.getInstance().getTokenUserId().equals("01897")) {
            return true;
        }
        Integer count = dao.selectArrangementPermission(TokenUtil.getInstance().getTokenUserId());
        return null != count && count > 0;
    }
}
