<template>
    <el-row :gutter="5">
        <el-col :span="8">
            <TargetTree v-if="isShowTree" :targetTreeData="targetTreeData" @treeNodeClick="treeNodeClick" />
        </el-col>
        <el-col :span="16">
            <PageLayer>
                <template #header class="hd-cl">
                    <el-button type="primary" icon="Plus" @click="resetForm(ruleFormRef)"
                        style="margin-left: 10px">新增</el-button>
                    <el-button type="primary" icon="Edit" @click="editForm(ruleFormRef)"
                        style="margin-left: 10px">编辑</el-button>
                    <el-button type="primary" icon="Check" @click="submitForm(ruleFormRef)"
                        style="margin-left: 10px">保存</el-button>
                    <el-button type="primary" icon="Refresh" @click="resetForm(ruleFormRef)"
                        style="margin-left: 10px">重置</el-button>
                </template>
                <template #main>
                    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                        :size="formSize" status-icon :disabled="isShowForm">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="指标名称" prop="name">
                                    <el-input v-model="ruleForm.name" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="指标编码" prop="id">
                                    <el-input v-model="ruleForm.id" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="父级编码" prop="pid">
                                    <el-input v-model="ruleForm.pid" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="指标序号" prop="sort">
                                    <el-input v-model="ruleForm.sort" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="总分" prop="score">
                                    <el-input v-model="ruleForm.score" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="所占比率" prop="ratio" :disabled="true">
                                    <el-input v-model="ruleForm.ratio" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="对接类型">
                                    <el-select v-model="ruleForm.type" placeholder="请选择类型">
                                        <el-option label="V1" value="0" />
                                        <el-option label="V2" value="1" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="状态" prop="state">
                                    <el-select v-model="ruleForm.state" placeholder="请选择状态">
                                        <el-option label="开启" value="Y" />
                                        <el-option label="关闭" value="N" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="启用时间">
                                    <el-form-item prop="openTime">
                                        <el-date-picker v-model="ruleForm.openTime" type="date" label="选择时间"
                                            placeholder="选择时间" style="width: 100%" />
                                    </el-form-item>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="责任科室" prop="deptCode">
                                    <el-select-v2 ref="deptInfoRef" v-model="ruleForm.deptCode" clearable remote filterable
                                        :remote-method="deptMethod" :options="deptWardList" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="责任人" prop="opId">
                                    <el-select-v2 ref="opInfoRef" v-model="ruleForm.opId" clearable remote filterable
                                        :remote-method="empMethod" :options="empList" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="是否叶子节点" prop="isLeaf">
                            <el-switch v-model="ruleForm.isLeaf" active-value="1" inactive-value="0" active-color="#13ce66"
                                inactive-color="#ff4949" @change='changeNode(ruleFormRef)' />
                        </el-form-item>
                        <el-form-item label="指标定义" prop="definition">
                            <el-input v-model="ruleForm.definition" type="textarea" />
                        </el-form-item>
                        <el-form-item label="评审方法" prop="method">
                            <el-input v-model="ruleForm.method" type="textarea" />
                        </el-form-item>
                        <el-form-item label="计分细则" prop="scoreRule">
                            <el-input v-model="ruleForm.scoreRule" type="textarea" />
                        </el-form-item>
                        <el-form-item label="数据来源" prop="source">
                            <el-input v-model="ruleForm.source" type="textarea" />
                        </el-form-item>
                        <el-divider />
                        <el-form ref="ruleFormRef" label-width="120px" :model="sqlForm" class="demo-ruleForm"
                            :size="formSize">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="开始时间">
                                        <el-form-item prop="startTime">
                                            <el-date-picker v-model="sqlForm.startTime" type="date" label="选择时间"
                                                placeholder="选择时间" format="YYYYMMDD" value-format="YYYYMMDD" />
                                        </el-form-item>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="结束时间">
                                        <el-form-item prop="endTime">
                                            <el-date-picker v-model="sqlForm.endTime" type="date" label="选择时间"
                                                placeholder="选择时间" format="YYYYMMDD" value-format="YYYYMMDD" />
                                        </el-form-item>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="8">
                                    <el-form-item label="公式-分子结果" prop="childResult">
                                        <el-input v-model="sqlForm.childResult" type="textarea" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="公式-分母结果" prop="momResult">
                                        <el-input v-model="sqlForm.momResult" type="textarea" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="分子/分母-结果" prop="calcResult">
                                        <el-input v-model="sqlForm.calcResult" type="textarea" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item>
                                        <el-button type="primary" @click="sqlEdit(ruleFormRef)"> 指标sql编辑 </el-button>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item>
                                        <el-button type="primary" @click="sqlExecute(ruleFormRef)"> 指标运行结果 </el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-form>
                </template>
            </PageLayer>
        </el-col>
    </el-row>

    <el-drawer :title="'Sql编辑'" v-model="isSqlEdit" size="80%" destroy-on-close>
        <SqlEditPage :sqlEditData="sqlEditData" />
    </el-drawer>
</template>
<script setup name="TargetDictConfig" lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import TargetTree from '../target-comm/targetTree.vue'
import SqlEditPage from '../target-comm/SqlEditPage.vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatDate } from '../../../utils/date'
import { clone } from '../../../utils/clone'
import PageLayer from '../../../layout/PageLayer.vue'
import { queryDept } from '../../../api/public-api'
import { selectTargetDict, selectTargetDictTree, saveTargetDict } from '../../../api/target-management/target-dict'
import { employeeList } from "../../../api/zhu-yuan-yi-sheng/pat-info-query"
import { targetSqlExecute } from '../../../api/target-management/target-sql'

const targetTreeData = ref({
    data: [{}],
    height: 900,
})

const isShowTree = ref(false)
const isShowForm = ref(false)
const nowDay = new Date()
const ds = formatDate(nowDay)
const deptWardList = ref([])
const empList = ref([])
const deptInfoRef = ref()
const opInfoRef = ref()

const isSqlEdit = ref(false)
let sqlEditData = ref({
    id: '', // 指标编码
    name: '', // 指标名称
    pid: '', // 父级编码
    sort: '', // 指标序号
    calcChild: '', // 计算分子sql
    calcMom: '', // 计算分母sql
})

const queryParam = reactive({
    id: '', // 指标编码
    name: '', // 指标名称
    pid: '', // 父级编码
    sort: '', // 指标序号
    type: '', // 对接类型
    state: '', // 状态
    openTime: '', // 启用时间
    deptId: '', // 责任科室id
    source: '', // 数据来源
    calcChild: '', // 计算分子sql
    calcMom: '', // 计算分母sql
    isLeaf: '', //是否叶子节点（0：否， 1：是）
})

onMounted(() => {
    nextTick(() => {
        qeryTargetDictTree()
        deptMethod('')
        empMethod('')
    })
})

const deptMethod = (val: string) => {
    queryDept(val).then((res: any) => {
        deptWardList.value = res
    })
}

const empMethod = (val: string) => {
    employeeList(val).then((res: any) => {
        empList.value = res
    })
}

// 查询指标字典树
const qeryTargetDictTree = () => {
    isShowTree.value == true ? false : true
    queryParam.id = '';
    queryParam.pid = '';
    selectTargetDictTree(queryParam)
        .then((res: any) => {
            targetTreeData.value.data = res
            isShowTree.value = true
        });
}

// ------  指标字典新增，修改保存表单开始  ------
// ruleForm.value.name = '123'
// ruleForm.name = '21312'
let ruleForm = $ref({
    id: '', // 指标编码
    name: '', // 指标名称
    pid: '', // 父级编码
    sort: '', // 指标序号
    score: '', // 总分
    ratio: '', // 所占比率
    type: '0', // 对接类型
    state: 'Y', // 状态
    openTime: ds, // 启用时间
    dept: '', // 责任科室
    deptCode: '', // 责任科室id
    op: '', // 责任人
    opId: '', // 责任人id
    definition: '', // 指标定义
    method: '', // 评审方法
    scoreRule: '', // 计分细则
    source: '', // 数据来源
    isLeaf: '0', // 是否叶子节点（0：否， 1：是）
    calcChild: '', // 计算-分子
    calcMom: '', // 计算-分母
})

let sqlForm = $ref({
    id: '', // 指标编码
    pid: '', // 父级编码
    calcChild: '', // 计算分子sql
    calcMom: '', // 计算分母sql
    startTime: '', // 计算开始时间
    endTime: '', // 计算结束时间
    childResult: '', // 计算分子结果
    momResult: '', // 计算分母结果
    calcResult: '' // 计算结果
})

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()

const rules = $ref<FormRules>({
    name: [
        { required: true, message: '请填写指标名称', trigger: 'blur' },
        { min: 1, max: 256, message: '指标名称长度范围1-256个字符', trigger: 'blur' },
    ],
    id: [
        { required: true, message: '请填写指标id', trigger: 'blur' },
        { min: 1, max: 12, message: '指标id长度范围1-12个字符', trigger: 'blur' },
    ],
    pid: [
        { required: true, message: '请填写指标父id', trigger: 'blur' },
        { min: 1, max: 12, message: '指标父id长度范围1-12个字符', trigger: 'blur' },
    ],
    sort: [
        { min: 0, max: 12, message: '指标序号长度范围0-12个字符', trigger: 'blur' },
    ],
    score: [
        { required: true, message: '请填写指标总分', trigger: 'blur' },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value) == false) {
                    callback(new Error("请输入正整数或两位小数"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        }
    ],
    ratio: [
        { min: 0, max: 48, message: '指标所占比例长度范围0-48个字符', trigger: 'blur' },
    ],
    definition: [
        { required: false, message: '请填写指标定义', trigger: 'blur' },
    ],
    method: [
        { required: false, message: '请填写评审方法', trigger: 'blur' },
    ],
    scoreRule: [
        { required: false, message: '请填写计分细则', trigger: 'blur' },
    ]
})

// 需要添加的叶子节点的校验
const leafRuleFields = ['definition', 'method', 'scoreRule']

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 处理叶子节点验证
    await leafRulesChange(formEl)

    await formEl.validate((valid, fields) => {
        if (valid) {
            ruleForm.dept = deptInfoRef.value.states.selectedLabel
            ruleForm.op = opInfoRef.value.states.selectedLabel
            saveTargetDict(ruleForm).then((res: any) => {
                if (res) {
                    nextTick(() => {
                        qeryTargetDictTree()

                        if (!isShowForm.value) {
                            isShowForm.value = true
                        }
                    })
                } else {
                    qeryTargetDictTree()
                    return
                }
            });

        } else {
            return
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return

    if (isShowForm.value) {
        isShowForm.value = false
    }

    formEl.resetFields()

    sqlForm.startTime = ''
    sqlForm.endTime = ''
    sqlForm.childResult = ''
    sqlForm.momResult = ''
    sqlForm.calcResult = ''
}

const changeNode = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await leafRulesChange(formEl)
}

// 叶子节点校验
const leafRulesChange = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 父节点
    if (ruleForm.isLeaf === '0') {
        // 取消叶子节点的字典值校验
        leafRuleFields.forEach(e => {
            if (rules[e]) {
                rules[e][0].required = false
            }
        })
        formEl.clearValidate(leafRuleFields)
    } else { // 叶子节点
        // 增加叶子节点的字典值校验
        leafRuleFields.forEach(e => {
            if (rules[e]) {
                rules[e][0].required = true
            }
        })
    }
}

const editForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    if (isShowForm.value) {
        isShowForm.value = false
        if ('1' === ruleForm.isLeaf) {
            changeNode(formEl)
        }
    }
}

// ------  指标字典新增，修改保存表单结束  ------

// ------  接收树页面传来的数据 -------
const treeNodeClick = (data: any, node: any, obj: any) => {
    if (node.data) {

        sqlForm.startTime = ''
        sqlForm.endTime = ''
        sqlForm.childResult = ''
        sqlForm.momResult = ''
        sqlForm.calcResult = ''

        queryParam.id = node.data.id
        queryParam.pid = node.data.pid
        selectTargetDict(queryParam)
            .then((res: any) => {
                if (res) {
                    nextTick(() => {
                        isShowForm.value = true
                        ruleForm = clone(res[0])
                        ruleFormRef.value?.resetFields()
                        ruleFormRef.value?.clearValidate()
                        leafRulesChange(ruleFormRef.value)
                    })
                }
            });


    }
}

// ------------------------- sql编辑 -----------------------
const sqlEdit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    if (ruleForm.id === '') {
        ElMessage({
            type: "info",
            message: "指标信息不全，请确认！",
            duration: 2500,
            showClose: true,
        });
        return
    }
    if (ruleForm.isLeaf === '0') {
        ElMessage({
            type: "info",
            message: "不是基础指标，不需要编写sql，请确认!",
            duration: 2500,
            showClose: true,
        });
        return
    }

    isSqlEdit.value = true
    sqlEditData.value = ruleForm

}
// --------------- sql编写结束 ------------

// --------------- sql运行 ----------------
const sqlExecute = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 验证是否填写完整
    if (ruleForm.id === '') {
        ElMessage({
            type: "info",
            message: "指标信息不全，请确认！",
            duration: 2500,
            showClose: true,
        });
        return
    }
    if (ruleForm.isLeaf === '0') {
        ElMessage({
            type: "info",
            message: "不是基础指标，不需要执行sql，请确认！",
            duration: 2500,
            showClose: true,
        });
        return
    }

    if (ruleForm.calcChild === '') {
        ElMessage({
            type: "info",
            message: "未编写sql，请联系管理员编写!",
            duration: 2500,
            showClose: true,
        });
        return
    }

    if (sqlForm.startTime === '' || sqlForm.endTime === '') {
        ElMessage({
            type: "info",
            message: "时间条件未选择，请确认！",
            duration: 2500,
            showClose: true,
        });
        return
    }

    sqlForm.id = ruleForm.id
    sqlForm.pid = ruleForm.pid
    sqlForm.calcChild = ruleForm.calcChild
    sqlForm.calcMom = ruleForm.calcMom
    targetSqlExecute(sqlForm)
        .then((res: any) => {
            let r = JSON.parse(JSON.stringify(res))
            sqlForm.childResult = r.r1
            sqlForm.momResult = r.r2
            sqlForm.calcResult = r.r3

        });

}

</script>
<style lang="scss" scoped deep>
.hd-cl {
    margin-bottom: 1px !important;
}
</style>