package thyyxxk.webserver.service.dictionary;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.dao.his.dictionary.MedicalTechnologyDao;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.dictionary.medicaltechnology.MedicalTechnologyItem;
import thyyxxk.webserver.entity.dictionary.medicaltechnology.QueryRequest;
import thyyxxk.webserver.service.hutoolcache.DeptCache;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.util.Date;
import java.util.List;

@Service
public class MedicalTechnologyService {
    private final MedicalTechnologyDao dao;
    private final DeptCache deptCache;

    @Autowired
    public MedicalTechnologyService(MedicalTechnologyDao dao, DeptCache deptCache) {
        this.dao = dao;
        this.deptCache = deptCache;
    }

    public List<CodeName> getDeptSelections() {
        return dao.getDeptSelections();
    }

    public List<MedicalTechnologyItem> queryQualifiedItems(QueryRequest request) {
        QueryWrapper<MedicalTechnologyItem> wrapper = new QueryWrapper<>();
        wrapper.eq("category", request.getCategory());
        if (StringUtil.notBlank(request.getItemCode())) {
            wrapper.eq("item_code", request.getItemCode());
        }
        if (StringUtil.notBlank(request.getDeptCode())) {
            wrapper.eq("dept_code", request.getDeptCode());
        }
        List<MedicalTechnologyItem> list = dao.selectList(wrapper);
        list.forEach(item -> item.setSurgeryTypeName(getTypeName(item.getSurgeryType())));
        return list;
    }

    public String saveTechnologyCatalogue(MedicalTechnologyItem body) {
        body.setOpStaff(TokenUtil.getInstance().getTokenUserId());
        body.setDeptName(deptCache.get(body.getDeptCode()).getName());
        if (null == body.getId()) {
            dao.insert(body);
        } else {
            body.setOpDate(new Date());
            dao.updateById(body);
        }
        return "操作成功。";
    }

    public String updateDelFlag(MedicalTechnologyItem body) {
        body.setDelFlag(body.getDelFlag() == 0 ? 1 : 0);
        body.setOpStaff(TokenUtil.getInstance().getTokenUserId());
        body.setOpDate(new Date());
        dao.updateById(body);
        return "操作成功。";
    }

    private String getTypeName(Integer type) {
        if (null == type) {
            return null;
        }
        switch (type) {
            case 1:
                return "手术";
            case 2:
                return "介入治疗";
            case 3:
                return "治疗性操作";
            case 4:
                return "诊断性操作";
            default:
                return null;
        }
    }
}
