<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="addForm(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="rulesForm" 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" minlength="1" maxlength="256" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="指标编码" prop="id">
                  <el-input v-model="ruleForm.id" minlength="1" maxlength="12" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="父级编码" prop="pid">
                  <el-input v-model="ruleForm.pid" minlength="1" maxlength="12" show-word-limit />
                </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" maxlength="12" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总分" prop="score">
                  <el-input v-model="ruleForm.score" placeholder="请输入正整数或两位小数" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="所占比率" prop="ratio" :disabled="true">
                  <el-input v-model="ruleForm.ratio" minlength="0" maxlength="48" show-word-limit />
                </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" aria-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-row>
              <el-col :span="4">
                <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-col>
              <el-col :span="10" v-show="ruleForm.isLeaf === '1'">
                <el-form-item label="分子" prop="childId">
                  <el-select v-model="ruleForm.childId" placeholder="请选择报表分子" filterable clearable>
                    <el-option v-for="item in reportIdOptions" :key="item.code" :label="item.name" :value="item.code">
                      <span style="float: left">{{ item.code }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px; ">
                        {{ item.name }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10" v-show="ruleForm.isLeaf === '1'">
                <el-form-item label="分母" prop="momId">
                  <el-select v-model="ruleForm.momId" placeholder="请选择报表分母" filterable clearable>
                    <el-option v-for="item in reportIdOptions" :key="item.code" :label="item.name" :value="item.code">
                      <span style="float: left">{{ item.code }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px; ">
                        {{ item.name }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <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" :rows="4" />
            </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" placeholder="请描述指标数据来源条件，比如：诊断包含xxx, 诊断编码是xxx等等" />
            </el-form-item>
            <el-divider />
            <el-form ref="upFormRef" label-width="180px" :model="sqlForm" class="demo-ruleForm" :size="formSize">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="开始年份">
                    <el-form-item prop="startTime">
                      <el-date-picker v-model="sqlForm.startTime" type="year" aria-label="选择年份" placeholder="选择年份"
                        format="YYYY" value-format="YYYY" :disabled="false" />
                    </el-form-item>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="结束年份">
                    <el-form-item prop="endTime">
                      <el-date-picker v-model="sqlForm.endTime" type="year" aria-label="选择年份" placeholder="选择年份"
                        format="YYYY" value-format="YYYY" :disabled="false" />
                    </el-form-item>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4">
                  <el-form-item>
                    <el-button type="primary" @click="sqlEdit(ruleFormRef)"> 指标sql编辑</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item>
                    <el-button type="primary" @click="sqlExecute(ruleFormRef)"> 指标运行结果</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item>
                    <el-button type="primary" @click="handWrite()"> 结果手动填写</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item>
                    <el-button type="primary" @click="saveTargetDictResult()"> 指标结果保存</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item>
                    <el-button type="primary" @click="queryTargetReportResult()"> 指标结果查询</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-form ref="upFormRef" label-width="180px" :model="sqlForm" class="demo-ruleForm" :size="formSize"
              :disabled="isShowTargetResult" v-show="isShowTargetResult">
              <el-row v-for="item in resultList">
                <el-col :span="8">
                  <el-form-item :label="item.childLabel" :prop="item.childLabel + item.index">
                    <el-input v-model="item.childResult" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="item.momLabel" :prop="item.momLabel + item.index">
                    <el-input v-model="item.momResult" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="item.calcLabel" :prop="item.calcLabel + item.index">
                    <el-input v-model="item.calcResult" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-form ref="upFormRef" label-width="120px" :model="sqlForm" class="demo-ruleForm" :size="formSize"
              v-show="isShowHandWrite">
              <el-row v-for="e in 4">
                <el-col :span="6">
                  <el-form-item :label="'年份' + e" :prop="'year' + e" :rules="[{ type: 'number', message: '年份必须是数字' },]">
                    <el-input v-model.number="sqlForm['year' + e]" minlength="4" maxlength="4" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="'分子结果' + e" :prop="'childResult' + e">
                    <el-input v-model="sqlForm['childResult' + e]" minlength="1" maxlength="12" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="'分母结果' + e" :prop="'momResult' + e">
                    <el-input v-model="sqlForm['momResult' + e]" minlength="1" maxlength="12" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="'分子/分母-结果' + e" :prop="'calcResult' + e">
                    <el-input v-model="sqlForm['calcResult' + e]" minlength="1" maxlength="12" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-row v-show="isShowQtResult">
              <el-table :data="QtResultData" stripe border highlight-current-row row-key="childKey" height="200"
                style="width: 100%">
                <el-table-column prop="year" label="年份" header-align="center" />
                <el-table-column prop="dataType" label="数据方式" header-align="center">
                  <template #default="scope">
                    {{ scope.row.dataType == '1' ? 'sql统计' : '手动输入' }}
                  </template>
                </el-table-column>
                <el-table-column prop="childResult" label="分子结果" header-align="center" />
                <el-table-column prop="momResult" label="分母结果" header-align="center" />
                <el-table-column prop="calcResult" label="计算结果" header-align="center" />
                <el-table-column prop="op" label="统计人员" header-align="center" />
                <el-table-column prop="opTime" label="统计时间" header-align="center" width="200" />
              </el-table>
            </el-row>
          </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, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { clone } from '@/utils/clone'
import { formatDate } from '@/utils/date'
import PageLayer from '../../../layout/PageLayer.vue'
import { queryDept } from '@/api/public-api'
import { selectTargetDictById, selectTargetDictTree, saveTargetDict } from '@/api/target-management/target-dict'
import { selectTargetZbReportId } from '@/api/target-management/report-dict'
import { employeeList } from "@/api/zhu-yuan-yi-sheng/pat-info-query"
import {
  targetSqlExecuteById,
  saveTargetReportResult,
  selectTargetReportResult
} from '@/api/target-management/target-sql'

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

const isShowTree = ref(false)
const isShowForm = ref(false)
// 是否显示指标sql运行结果
const isShowTargetResult = ref(false)
// 是否显示指标手动输入结果
const isShowHandWrite = ref(false)
// 是否显示指标查询结果
const isShowQtResult = ref(false)
const nowDay = new Date()
const ds = formatDate(nowDay)
const deptWardList = ref([])
const empList = ref([])
const deptInfoRef = ref()
const opInfoRef = ref()
const reportIdOptions = ref([{ code: '', name: '' }])

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

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

onMounted(() => {
  nextTick(() => {
    qeryTargetDictTree()
    queryTargetZbReportId()
    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 queryTargetZbReportId = () => {
  selectTargetZbReportId('zb').then((res: any) => {
    reportIdOptions.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: '1', // 是否叶子节点（0：否， 1：是）
  calcChild: '', // 计算-分子
  calcMom: '', // 计算-分母
  childId: '',
  momId: '',
})

let sqlForm = reactive({
  id: '', // 指标编码
  pid: '', // 父级编码
  calcChild: '', // 计算分子sql
  calcMom: '', // 计算分母sql
  startTime: '', // 计算开始时间
  endTime: '', // 计算结束时间
  year1: '', // 计算年份1
  childResult1: '', // 计算分子结果1
  momResult1: '', // 计算分母结果1
  calcResult1: '', // 计算结果1
  year2: '', // 计算年份2
  childResult2: '', // 计算分子结果2
  momResult2: '', // 计算分母结果2
  calcResult2: '', // 计算结果2
  year3: '', // 计算年份3
  childResult3: '', // 计算分子结果3
  momResult3: '', // 计算分母结果3
  calcResult3: '', // 计算结果3
  year4: '', // 计算年份4
  childResult4: '', // 计算分子结果4
  momResult4: '', // 计算分母结果4
  calcResult4: '', // 计算结果4
  childResult: '',
  momResult: '',
  calcResult: '',
  childId: '',
  momId: '',
})

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

const rulesForm = 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: true, message: '请填写指标定义', trigger: 'blur' },
  ],
  method: [
    { required: true, message: '请填写评审方法', trigger: 'blur' },
  ],
  scoreRule: [
    { required: true, 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.value.dept = deptInfoRef.value.states.selectedLabel
      ruleForm.value.op = opInfoRef.value.states.selectedLabel
      saveTargetDict(ruleForm.value).then((res: any) => {
        if (res) {
          nextTick(() => {
            qeryTargetDictTree()

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

    } else {
      return
    }
  })
}

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

  if (queryParam.id === '') {
    ElMessage({
      type: "info",
      message: "请选择一个指标！",
      duration: 2500,
      showClose: true,
    });
    return
  }

  if (queryParam.isLeaf === '1') {
    ElMessage({
      type: "info",
      message: "请选择一个父节点指标！",
      duration: 2500,
      showClose: true,
    });
    return
  }

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

  formEl.resetFields()

  // 新增自动映射父指标id作为子指标的父id
  ruleForm.value.pid = queryParam.id
  sqlForm.startTime = ''
  sqlForm.endTime = ''
  sqlForm.childResult = ''
  sqlForm.momResult = ''
  sqlForm.calcResult = ''
}

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

  if (isShowForm.value) {
    isShowForm.value = false
  }
  if (isShowTargetResult.value) {
    isShowTargetResult.value = false
  }
  if (isShowHandWrite.value) {
    isShowHandWrite.value = false
  }
  if (isShowQtResult.value) {
    isShowQtResult.value = false
  }

  sqlForm.startTime = ''
  sqlForm.endTime = ''
  resultList.value = []

  formEl.resetFields()
  upFormRef.value?.resetFields()
}

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

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

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

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

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

    resultList.value = []
    if (isShowTargetResult.value === false) {
      isShowTargetResult.value = true
    }

    queryParam.id = node.data.id
    queryParam.pid = node.data.pid
    selectTargetDictById(queryParam)
      .then((res: any) => {
        if (res) {
          nextTick(() => {
            isShowForm.value = true
            ruleForm.value = res
            // 获取点击树的是否叶子节点数据
            queryParam.isLeaf = ruleForm.value.isLeaf
            ruleFormRef.value?.resetFields()
            ruleFormRef.value?.clearValidate()
            leafRulesChange(ruleFormRef.value)

            upFormRef.value?.resetFields()
            // 获取指标报表结果
            queryTargetReportResult()
          })
        }
      });

  }
}

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

  isSqlEdit.value = true
  sqlEditData.value.id = ruleForm.value.id
  sqlEditData.value.pid = ruleForm.value.pid
  sqlEditData.value.name = ruleForm.value.name
  sqlEditData.value.calcChild = ruleForm.value.calcChild
  sqlEditData.value.calcMom = ruleForm.value.calcMom
  sqlEditData.value.childId = ruleForm.value.childId
  sqlEditData.value.momId = ruleForm.value.momId
  sqlEditData.value.sort = ruleForm.value.sort

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

// --------------- sql运行 ----------------
interface DataType {
  id: string,
  pid: string,
  childLabel: string,
  childResult: string,
  momLabel: string,
  momResult: string,
  calcLabel: string,
  calcResult: string,
  index: number,
  year: number,
  dataType: string, // 数据统计类型：1 sql计算获得； 2 手动输入填写获得
}

const resultList = ref([{
  id: '',
  pid: '',
  childLabel: '',
  childResult: '',
  momLabel: '',
  momResult: '',
  calcLabel: '',
  calcResult: '',
  index: 0,
  year: 0,
  dataType: '',
}])

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

  if (ruleForm.value.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
  }

  if (isShowHandWrite.value) {
    isShowHandWrite.value = false
  }
  if (isShowTargetResult.value === false) {
    isShowTargetResult.value = true
  }

  sqlForm.id = ruleForm.value.id
  sqlForm.pid = ruleForm.value.pid
  sqlForm.childId = ruleForm.value.childId
  sqlForm.momId = ruleForm.value.momId
  targetSqlExecuteById(sqlForm)
    .then((res: any) => {
      resultList.value = res
    });
}

// ------------ 手动填值 ---------
const handWrite = () => {
  upFormRef.value?.resetFields()
  if (isShowTargetResult.value) {
    isShowTargetResult.value = false
  }
  resultList.value = [] as any
  isShowHandWrite.value = true
}

// ------------ 统计结果保存 --------------
const saveTargetDictResult = () => {

  if (ruleForm.value.id === '') {
    ElMessage({
      type: "info",
      message: "指标信息不全，请确认！",
      duration: 2500,
      showClose: true,
    });
    return
  }

  if (QtResultData) {
    ElMessageBox.confirm('已存在统计结果，请确认是否继续保存统计结果？', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
    })
      .then(() => {
        let targetResultList = [] as any
        if (resultList.value.length > 0) {
          targetResultList = clone(resultList.value)
        } else {
          for (let i = 1; i <= 4; i++) {
            if (sqlForm['year' + i] && sqlForm['calcResult' + i]) {
              let handWriteData = {} as DataType
              handWriteData.id = ruleForm.value.id
              handWriteData.pid = ruleForm.value.pid
              handWriteData.dataType = '2'
              handWriteData.year = sqlForm['year' + i]
              handWriteData.childResult = sqlForm['childResult' + i]
              handWriteData.momResult = sqlForm['momResult' + i]
              handWriteData.calcResult = sqlForm['calcResult' + i]
              targetResultList.push(handWriteData)
            }
          }
        }

        if (targetResultList.length > 0) {
          saveTargetReportResult(targetResultList)
            .then((res: any) => {
              if (res) {
                ElMessage({
                  type: "success",
                  message: "保存统计结果成功！",
                  duration: 2500,
                  showClose: true,
                });
                return
              }
            });

        } else {
          ElMessage({
            type: "info",
            message: "保存统计结果为空，请确认！",
            duration: 2500,
            showClose: true,
          });
          return
        }
      }).catch(() => {
      })
  }
}

// -------------------- 指标统计结果查询 --------------------
let QtResultData = ref([])
const queryTargetReportResult = () => {

  if (ruleForm.value.id === '') {
    ElMessage({
      type: "info",
      message: "指标信息不全，请确认！",
      duration: 2500,
      showClose: true,
    });
    return
  }

  if (isShowHandWrite.value) {
    isShowHandWrite.value = false
  }
  if (isShowTargetResult.value) {
    isShowTargetResult.value = false
  }

  let queryData = {
    id: '',
    pid: '',
    startTime: '',
    endTime: '',
  }
  queryData.id = ruleForm.value.id
  queryData.pid = ruleForm.value.pid
  selectTargetReportResult(queryData)
    .then((res: any) => {
      if (isShowQtResult.value === false) {
        isShowQtResult.value = true
      }
      QtResultData.value = res
    });
}

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