<template>
    <div class="add-treatment">
        <el-container style="height: 100vh; display: flex; flex-direction: column;">
            <el-main style="padding: 0; flex: 1; display: flex; flex-direction: column;">
                <div class="content-wrapper">
                    <h2 class="page-title">添加治疗记录</h2>

                    <div class="treatment-container">
                        <!-- 羊只信息只读展示 -->
                        <div class="sheep-info-section">
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <div class="info-item">
                                        <strong>耳号：</strong>{{ sheepInfo.sheepNo || '–' }}
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="info-item">
                                        <strong>性别：</strong>{{ sheepInfo.gender }}
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="info-item">
                                        <strong>品种：</strong>{{ sheepInfo.variety || '–' }}
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="info-item">
                                        <strong>羊只类别：</strong>{{ sheepInfo.sheepType || '–' }}
                                    </div>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <div class="info-item">
                                        <strong>月龄：</strong>{{ sheepInfo.monthAge ?? '–' }} &nbsp;月
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="info-item">
                                        <strong>胎次：</strong>{{ sheepInfo.parity ?? '–' }}
                                    </div>
                                </el-col>
                            </el-row>
                        </div>

                        <el-form ref="treatmentRef" :model="form" :rules="rules" label-width="140px" status-icon
                            size="large" class="treatment-form">
                            <!-- 疾病和诊疗信息 -->
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="事件日期" prop="datetime">
                                        <el-date-picker v-model="form.datetime" type="date" placeholder="选择日期"
                                            style="width: 100%;" :disabled="true" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="发病日期" prop="begindate">
                                        <el-date-picker v-model="form.begindate" type="date" placeholder="选择日期"
                                            style="width: 100%;" :disabled="true" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="疾病类型" prop="diseasePName">
                                        <span>{{ form.diseasePName }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="疾病子类型" prop="diseaseName">
                                        <span>{{ form.diseaseName }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="治疗结束日期" prop="enddate">
                                        <el-date-picker v-model="form.enddate" type="date" placeholder="选择日期"
                                            style="width: 100%" :disabled-date="disabledDate" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="治疗天数">
                                        <span>{{ treatDay || 0}} 天</span>
                                        <!-- <el-input :value="treatDay" readonly style="width: 100%;" /> -->
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="治疗结果" prop="result">
                                        <el-select v-model="form.result" placeholder="请选择治疗结果" style="width: 100%;">
                                            <el-option v-for="item in diag_status" :key="item.value" :label="item.label"
                                                :value="item.value" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="转入羊舍" prop="sheepfoldId">
                                        <el-select v-model="form.sheepfoldId" placeholder="请选择转入羊舍"
                                            style="width: 100%;">
                                            <el-option v-for="item in sheepfolds" :key="item.id" :label="item.name"
                                                :value="item.id" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item label="备注" prop="comments">
                                <el-input type="textarea" :rows="3" v-model="form.comments" placeholder="请输入备注" />
                            </el-form-item>

                            <div class="form-footer">
                                <el-button @click="goBack">取消</el-button>
                                <el-button type="primary" @click="submitForm">确定</el-button>
                            </div>
                        </el-form>
                    </div>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import useTagsViewStore from "@/store/modules/tagsView.js"
import request from '@/utils/request'
import { listDisease } from '@/api/biosafety/disease'
import { getTreatment } from '@/api/biosafety/treatment'
import { listSheepfold_management } from "@/api/fileManagement/sheepfold_management"
import {  addDiagnosis } from "@/api/biosafety/diagnosis"

const { proxy } = getCurrentInstance()
const { diag_status } = proxy.useDict( "diag_status")



const route = useRoute()
const router = useRouter()
const { tId, sId } = route.query

const sheepInfo = ref({
    sheepNo: null,
    gender: '',
    variety: '',
    sheepType: '',
    monthAge: null,
    parity: null,
    breed: '',
    lactDay: null,
    gestDay: null
})
const sheepfolds = ref([])

function getSheepInfo() {
    if (!sId) return
    request.get(`/sheep_file/sheep_file/${sId}`).then(response => {
        const data = response.data
        sheepInfo.value = {
            sheepNo: data.bsManageTags,
            gender: data.gender,
            variety: data.variety,
            sheepType: data.name,
            monthAge: data.monthAge,
            parity: data.parity,
            breed: data.breed,
        }
        
    })
}

function getTreatmentInfo() {
    if (!tId) return
    getTreatment(tId).then(response => {
        const data = response.data
        form.treatId = tId
        form.datetime = new Date()
        form.begindate = new Date(data.datetime)
        form.diseasePName = data.diseasePName
        form.diseaseId = data.diseaseId
        form.diseasePid = data.diseasePid
        form.diseaseName = data.diseaseName
    })
}

const parentDiseaseOptions = ref([])
const childDiseaseOptions = ref([])

function getDiseases() {
    listDisease().then(response => {
        const diseases = proxy.handleTree(response.data, "id", "pid")
        parentDiseaseOptions.value = diseases.filter(item => item.pid === 0)
    })
}

function handleDiseaseTypeChange(parentId) {
    if (!parentId) {
        childDiseaseOptions.value = []
        form.diseaseName = null
        return
    }
    listDisease({ pid: parentId }).then(response => {
        childDiseaseOptions.value = response.data
        form.diseaseName = null
    })
}

const form = reactive({
    datetime: new Date(),
    begindate: null,
    eventType: '',
    diseasePName: null,
    diseaseName: null,
    result: '',
    enddate: null,
    comments: '',
    sheepId: sId

})

const rules = {
    datetime: { required: true, message: '事件日期不能为空', trigger: 'change' },
    enddate: { required: true, message: '治疗日期不能为空', trigger: 'change' },
    sheepfoldId: { required: true, message: '转入羊舍不能为空', trigger: 'change' },
    result: { required: true, message: '治疗结果不能为空', trigger: 'change' }
}

const treatDay = computed(() => {
    if (!form.begindate || !form.enddate) return ''
    const onset = new Date(form.begindate)
    const end = new Date(form.enddate)
    const diffTime = end.getTime() - onset.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
})

function submitForm() {
    proxy.$refs.treatmentRef.validate((valid) => {
        if (valid) {
            const submitData = {
                ...form,
                datetime: form.datetime ? new Date(form.datetime).getTime() : null,
                begindate: form.begindate ? new Date(form.begindate).getTime() : null,
                endDate: form.endDate ? new Date(form.endDate).getTime() : null,
                treatDay: treatDay.value
            }
            addDiagnosis(submitData).then(response => {
                proxy.$modal.msgSuccess("诊断成功")
                open.value = false
                goBack()
            })
        } else {
            ElMessage.error("请完整填写表单信息！")
            return false
        }
    })
}

// 禁止选择今天以前的日期
const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7   // 8.64e7 = 24*60*60*1000
}

const useTagsStore = useTagsViewStore()
const currentTag = router.currentRoute.value
const goBack = () => {
    router.go(-1)
    useTagsStore.delVisitedView(currentTag)
}

onMounted(() => {
    getDiseases()
    getTreatmentInfo()
    getSheepInfo()
    listSheepfold_management().then(res => {
        sheepfolds.value = res.rows.map(item => ({ id: item.id, name: item.sheepfoldName }))
    })
})
</script>

<style scoped>
.add-treatment {
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.el-container {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.content-wrapper {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
}

.page-title {
    margin: 0 0 24px;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    text-align: center;
}

.treatment-container {
    max-width: 1200px;
    margin: 0 auto;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}

.sheep-info-section {
    background-color: #f5f7fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 32px;
}

.info-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.info-item strong {
    color: #606266;
    font-weight: 500;
    margin-right: 8px;
    width: 100px;
}

.info-item span {
    color: #303133;
    flex: 1;
}

.treatment-form {
    margin: 0 auto;
    padding: 0 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.el-form-item {
    margin-bottom: 24px;
}

.el-input,
.el-textarea,
.el-select {
    width: 100%;
}

.form-footer {
    margin-top: 40px;
    text-align: center;
}

.form-footer .el-button {
    padding: 12px 40px;
    font-size: 16px;
    border-radius: 6px;
}

@media (max-width: 768px) {
    .el-col {
        margin-bottom: 16px;
    }

    .el-row {
        margin-bottom: 16px;
    }

    .info-item {
        flex-direction: column;
        align-items: flex-start;
        margin-bottom: 12px;
    }

    .info-item strong {
        margin-bottom: 6px;
    }
}
</style>