<template>
  <page-layer>
    <template #header>
      <el-date-picker v-model="dateRange" type="monthrange" range-separator="至" start-placeholder="开始月份"
        end-placeholder="结束月份" style="width: 220px"></el-date-picker>
      <el-cascader v-model="setlCondition.dataInfo" :options="setlCondition.options" :props="{ expandTrigger: 'hover' }"
        @change="handleChange" :clearable="true" :filterable="true" placeholder="请选择险种">
      </el-cascader>
      <el-divider direction="vertical"></el-divider>
      <el-button icon="Search" type="primary" @click="fetchSetlinfos">查询</el-button>
      <el-button icon="Download" type="primary" @click="exportSetlinfoExcel">导出Excel</el-button>
      <el-button icon="TrendCharts" type="primary" @click="selectChart">分析图</el-button>
      <el-button icon="Histogram" type="primary" @click="showBarChart">费用趋势图</el-button>
      <el-button icon="TrendCharts" type="primary" @click="showTreeChart">人数树状图</el-button>
    </template>
    <template #main>
      <el-tabs type="border-card" v-model="setlCondition.selectType" @tab-click="handleClick">
        <el-tab-pane label="数据" name="first">
          <el-table :data="setlinfos" :height="tableHeight" border highlight-current-row row-key="childKey" show-summary
            :summary-method="getSummaries1" stripe @row-dblclick="fetchSetldetails">
            <el-table-column label="险种类型" prop="insurName" fixed header-align="center" width="130"></el-table-column>
            <el-table-column label="住院人次" prop="psnCount" align="center" header-align="center"></el-table-column>
            <el-table-column label="住院天数" prop="inDays" align="center" header-align="center"></el-table-column>
            <el-table-column label="平均住院日" prop="avgInDays" align="right" header-align="center"></el-table-column>
            <el-table-column label="总费用" prop="totalFee" align="right" header-align="center"></el-table-column>
            <el-table-column label="药品费用" prop="drugFee" align="right" header-align="center"></el-table-column>
            <el-table-column label="药品占比(%)" prop="drugFeeRatio" align="right" header-align="center"></el-table-column>
            <el-table-column label="耗材费用" prop="matFee" align="right" header-align="center"></el-table-column>
            <el-table-column label="耗材占比(%)" prop="matFeeRatio" align="right" header-align="center"></el-table-column>
            <el-table-column label="基本医疗统筹金额" prop="fundPooling" align="right" header-align="center"></el-table-column>
            <el-table-column label="大病基金" prop="bigIllFundPooling" align="right" header-align="center">
            </el-table-column>
            <el-table-column label="公务员基金支付" prop="civilServiceFund" align="right" header-align="center">
            </el-table-column>
            <el-table-column label="其他基金" prop="otherFunds" align="right" header-align="center"></el-table-column>
            <el-table-column label="全部基金" prop="allFunds" align="right" header-align="center"></el-table-column>
            <el-table-column label="个人账户支出" prop="acctPay" align="right" header-align="center"></el-table-column>
          </el-table>
          <el-dialog v-model="showSetldetails" :close-on-click-modal="false" :close-on-press-escape="false"
            :title="filterDialogTitle" width="80%">
            <div style="width: 130px; height: 36px; position: absolute; top: 16px; right: 60px">
              <el-button icon="Download" type="primary" @click="exportYbDetailExcel">导出Excel</el-button>
            </div>
            <el-table :data="setldetails.slice(pageSize * (currentPage - 1), pageSize * currentPage)" height="560"
              highlight-current-row stripe @row-dblclick="openSetlinfoComponent">
              <el-table-column fixed label="序号" type="index" width="40"></el-table-column>
              <el-table-column fixed label="姓名" prop="psnName" width="60"></el-table-column>
              <el-table-column fixed label="住院号" prop="patNo" width="70"></el-table-column>
              <el-table-column label="次数" prop="times" width="40"></el-table-column>
              <el-table-column label="科室" prop="psnCertType" width="100"></el-table-column>
              <el-table-column label="性别" prop="gendName" width="50"></el-table-column>
              <el-table-column label="出生日期" prop="brdy"></el-table-column>
              <el-table-column label="身份证" prop="certno"></el-table-column>
              <el-table-column label="主要诊断" prop="mainDiagnosis" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column label="主要手术" prop="mainOperation" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column label="参保地区" prop="insuplcAdmdvsName"></el-table-column>
              <el-table-column label="险种类型" prop="insutypeName"></el-table-column>
              <el-table-column label="人员类别" prop="psnTypeName"></el-table-column>
              <el-table-column label="就诊ID" prop="mdtrtId"></el-table-column>
              <el-table-column label="结算ID" prop="setlId"></el-table-column>
              <el-table-column label="入院时间" prop="begntime"></el-table-column>
              <el-table-column label="出院时间" prop="endtime"></el-table-column>
              <el-table-column label="结算时间" prop="setlTime"></el-table-column>
              <el-table-column label="医疗类别" prop="medTypeName"></el-table-column>
              <el-table-column label="总医疗费用" prop="medfeeSumamt"></el-table-column>
              <el-table-column label="总报销金额" prop="fundPaySumamt"></el-table-column>
              <el-table-column label="医疗救助" prop="mafPay"></el-table-column>
              <el-table-column label="个人账户支出" prop="acctPay"></el-table-column>
              <el-table-column label="个人现金支出" prop="psnCashPay"></el-table-column>
              <el-table-column label="大病支出" prop="hifmiPay"></el-table-column>
              <el-table-column label="西药费" prop="chargeWesternMedicine"></el-table-column>
              <el-table-column label="中成药费" prop="chargePatentMedicine"></el-table-column>
              <el-table-column label="中药饮片费" prop="chargeHerbal"></el-table-column>
              <el-table-column label="耗材费" prop="chargeSanitaryMaterial"></el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[15, 30, 45, 60]"
              :total="setldetails.length" layout="total, sizes, prev, pager, next, jumper" style="margin-top: 5px"
              @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
          </el-dialog>
          <el-dialog v-model="showSetlinfoComponent" :close-on-click-modal="false" title="结算信息" width="70%">
            <Setlinfo :setlinfo="currentSetldetail" />
          </el-dialog>
          <el-dialog v-model="showChart" :close-on-click-modal="false" title="费用趋势图" width="70%" top="40px" draggable>
            <BarChart :ybkf="barChangeData" />
          </el-dialog>
          <el-dialog v-model="treeChart" :close-on-click-modal="false" title="人数树状图" width="70%" top="40px" draggable>
            <div style="height: 35px">
              <el-autocomplete v-model="deptNo" value-key="name" :fetch-suggestions="querySearchDept"
                :trigger-on-focus="false" clearable class="inline-input w-50 m-2" style="width: 240px"
                placeholder="请输入关键字" @select="handleSelect">
                <template #prepend>科室</template>
              </el-autocomplete>
              <el-autocomplete v-model="doctorId" value-key="name" :fetch-suggestions="querySearchDoctor"
                :trigger-on-focus="false" clearable class="inline-input w-50 m-2" style="width: 240px"
                placeholder="请输入关键字" @select="handleSelect">
                <template #prepend>管床医生</template>
              </el-autocomplete>
              <el-input v-model="insurCode" clearable style="width: 240px" class="w-50 m-2">
                <template #prepend>医保类别</template>
              </el-input>
              <el-divider direction="vertical"></el-divider>
              <el-button icon="Search" type="primary" @click="selectTreeChart">查询</el-button>
              <el-button icon="Download" type="primary" @click="exportTreeRs">导出</el-button>
            </div>
            <div style="width: 100%; height: 700px" id="treedsf"></div>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="同比" name="second">
          <el-table :data="setlinfos" :height="tableHeight" border highlight-current-row row-key="childKey" show-summary
            :summary-method="getSummaries1">
            <el-table-column label="月份" prop="month" fixed align="center" header-align="center"></el-table-column>
            <el-table-column label="总费用" prop="zfy" header-align="center">
              <el-table-column label="今年" prop="zfy_jn" align="right" header-align="center"></el-table-column>
              <el-table-column label="去年" prop="zfy_qn" align="right" header-align="center"></el-table-column>
              <el-table-column label="同比" prop="zfy_tb" align="right" header-align="center"></el-table-column>
            </el-table-column>
            <el-table-column label="全部基金" prop="zjj" header-align="center">
              <el-table-column label="今年" prop="zjj_jn" align="right" header-align="center"></el-table-column>
              <el-table-column label="去年" prop="zjj_qn" align="right" header-align="center"></el-table-column>
              <el-table-column label="同比" prop="zjj_tb" align="right" header-align="center"></el-table-column>
            </el-table-column>
            <el-table-column label="药品费用" prop="ypf" header-align="center">
              <el-table-column label="今年" prop="ypf_jn" align="right" header-align="center"></el-table-column>
              <el-table-column label="去年" prop="ypf_qn" align="right" header-align="center"></el-table-column>
              <el-table-column label="同比" prop="ypf_tb" align="right" header-align="center"></el-table-column>
            </el-table-column>
            <el-table-column label="耗材费用" prop="clf" header-align="center">
              <el-table-column label="今年" prop="clf_jn" align="right" header-align="center"></el-table-column>
              <el-table-column label="去年" prop="clf_qn" align="right" header-align="center"></el-table-column>
              <el-table-column label="同比" prop="clf_tb" align="right" header-align="center"></el-table-column>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="环比" name="third">
          <el-table :data="setlinfos" :height="tableHeight" border highlight-current-row row-key="childKey" show-summary
            :summary-method="getSummaries1">
            <el-table-column label="月份" prop="month" align="center" fixed header-align="center"></el-table-column>
            <el-table-column label="总费用" prop="zfys" header-align="center">
              <el-table-column label="费用" prop="zfy" align="right" header-align="center"></el-table-column>
              <el-table-column label="环比" prop="zfy_hb" align="right" header-align="center"></el-table-column>
            </el-table-column>
            <el-table-column label="全部基金" prop="zjjs" header-align="center">
              <el-table-column label="费用" prop="zjj" align="right" header-align="center"></el-table-column>
              <el-table-column label="环比" prop="zjj_hb" align="right" header-align="center"></el-table-column>
            </el-table-column>
            <el-table-column label="药品费用" prop="ypfs" header-align="center">
              <el-table-column label="费用" prop="ypf" align="right" header-align="center"></el-table-column>
              <el-table-column label="环比" prop="ypf_hb" align="right" header-align="center"></el-table-column>
            </el-table-column>
            <el-table-column label="耗材费用" prop="clfs" header-align="center">
              <el-table-column label="费用" prop="clf" align="right" header-align="center"></el-table-column>
              <el-table-column label="环比" prop="clf_hb" align="right" header-align="center"></el-table-column>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-drawer :title="titleChart" v-model="qxtDrawer" size="80%">
        <el-row :gutter="10">
          <el-col :span="6">
            <div style="width: 100%; height: 400px" id="zfyDst"></div>
          </el-col>
          <el-col :span="6">
            <div style="width: 100%; height: 400px" id="zjjDst"></div>
          </el-col>
          <el-col :span="6">
            <div style="width: 100%; height: 400px" id="ypfDst"></div>
          </el-col>
          <el-col :span="6">
            <div style="width: 100%; height: 400px" id="clfDst"></div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <div style="width: 100%; height: 400px" id="rcpie"></div>
          </el-col>
          <el-col :span="8">
            <div style="width: 100%; height: 400px" id="zytsPie"></div>
          </el-col>
          <el-col :span="8">
            <div style="width: 100%; height: 400px" id="zfyPie"></div>
          </el-col>
        </el-row>
      </el-drawer>
    </template>
  </page-layer>
</template>

<script>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import store from '@/store'
import { getDateRangeFormatDate, formatDatetime } from '@/utils/date'
import {
  selectYbStatInfo,
  selectYbStatRatio,
  selectYbChart,
  selectYbStatDetail,
  querySettlementInfo,
  selectBarChangeData,
  selectTreeData
} from '@/api/medical-insurance/si-ybkf'
import { clone } from '@/utils/clone'
import { Export } from '@/utils/ExportExcel'
import { ElMessage, ElMessageBox } from 'element-plus'
import { downloadExcel } from '@/utils/excel'
import { pieUtilsOne, barUtilsTwo, barUtilsThree, treeChartRoot } from '@/utils/echarts-utils'
import Setlinfo from '../../../components/medical-insurance/setlinfo/Index.vue'
import BarChart from '../../../components/medical-insurance/ybkf/BarChart.vue'
import { selectSmallDept, selectDoctor } from '@/api/medical-insurance/si-yb-util'
import PageLayer from "@/layout/PageLayer";

export default {
  components: {
    PageLayer,
    Setlinfo,
    BarChart,
  },
  setup() {
    const storeU = useStore()
    const windowSize = storeU.state.app.windowSize
    const tableHeight = windowSize.h - 120
    const dateRange = ref([])
    const dateS = getDateRangeFormatDate(dateRange.value)

    const setlinfos = ref([])

    const qxtDrawer = ref(false)
    const titleChart = ref('图形')
    const chartData = ref([])
    const pieChartData = reactive({
      selectPie: '1',
    })

    const deptNo = ref('')
    const doctorId = ref('')
    const insurCode = ref('')

    const showChart = ref(false)
    const barChangeData = ref([])
    const showBarChart = (val) => {
      if (setlCondition.setlType === '11') {
        ElMessage({
          message: '门诊不参与排名！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      let selectInfo = clone(setlCondition)
      selectBarChangeData(selectInfo)
        .then((res) => {
          barChangeData.value = res
          showChart.value = true

          //月份
          let months = []
          //数据
          let dataBar = []
          //显示排名前几名
          let num = 15
          //单位
          let unit = '元'

          barChangeData.value.forEach((item) => {
            let d = []

            if (months.length === 0 || months[months.length - 1] !== item.yf) {
              months.push(item.yf)
            }

            d.push(item.totalFee)
            d.push(item.medins_type)
            d.push(item.yf)

            dataBar.push(d)
          })
          nextTick(() => {
            barUtilsThree(hightChart, '总费用(TOP' + num + ')', months, dataBar, num - 1, unit)
          })
        })
        .catch(() => {
          barChangeData.value = []
        })
    }

    const querySearchDept = async (str, cb) => {
      let results = await selectSmallDept({ str })
      if (results) {
        // 调用 callback 返回建议列表的数据
        cb(results)
      }
    }

    const querySearchDoctor = async (str, cb) => {
      let results = await selectDoctor({ str })
      if (results) {
        // 调用 callback 返回建议列表的数据
        cb(results)
      }
    }

    const handleSelect = (item) => {
    }

    const treeChart = ref(false)
    const treeData = ref([])
    const showTreeChart = (val) => {
      if (setlCondition.setlType === '11') {
        ElMessage({
          message: '门诊不参与统计！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        treeChart.value = false
        return
      }

      let selectData = clone(setlCondition)
      if (!selectData.startTime) {
        ElMessage({
          message: '请选择时间范围！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        treeChart.value = false
        return
      }
      treeChart.value = true

      selectTreeData(selectData).then((res) => {
        treeData.value = res
        deptNo.value = ''
        doctorId.value = ''
        insurCode.value = ''
        nextTick(() => {
          treeChartRoot(treedsf, '树', treeData.value, [])
        })
      })
    }

    const selectTreeChart = (val) => {
      treeChart.value = true
      let selectData = clone(setlCondition)
      selectData.dept = deptNo.value
      selectData.doctor = doctorId.value
      selectData.insurType = insurCode.value
      selectTreeData(selectData).then((res) => {
        treeData.value = res
        let searchData = [deptNo.value, doctorId.value, insurCode.value]
        nextTick(() => {
          treeChartRoot(treedsf, '树', treeData.value, searchData)
        })
      })
    }

    const setldetails = ref([])
    const showSetldetails = ref(false)

    const setlCondition = reactive({
      startTime: dateS.startTime,
      endTime: dateS.endTime,
      setlType: '21',
      selectType: 'first',
      insurType: null,
      dataInfo: null,
      options: initInsurOptions(),
    })

    const fetchSetldetails = (row) => {
      let selectInfo = clone(setlCondition)
      selectInfo.insurType = row.insurType
      selectYbStatDetail(selectInfo)
        .then((res) => {
          setldetails.value = res
          showSetldetails.value = true
        })
        .catch(() => {
          setldetails.value = []
        })
    }

    const filterDialogTitle = computed(() => {
      let yearL = setlCondition.startTime.substr(0, 4)
      const setlTypeName = filterSetlTypeName()
      return yearL + setlTypeName + '结算明细'
    })

    const showSetlinfoComponent = ref(false)
    const currentSetldetail = ref({})
    const openSetlinfoComponent = (row) => {
      const param = {
        psnNo: row.psnNo,
        mdtrtId: row.mdtrtId,
      }
      querySettlementInfo(param).then((res) => {
        currentSetldetail.value = res
        showSetlinfoComponent.value = true
      })
    }

    const fetchSetlinfos = () => {
      if (!dateRange.value) {
        ElMessage({
          message: '请选择时间范围！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      if (!setlCondition.dataInfo) {
        ElMessage({
          message: '请选择险种！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      setlCondition.setlType = setlCondition.dataInfo[0]
      setlCondition.insurType = setlCondition.dataInfo[1]

      setlCondition.startTime = formatDatetime(dateRange.value[0])
      setlCondition.endTime = formatDatetime(dateRange.value[1])

      let yearL = setlCondition.startTime.substr(0, 4)
      let yearR = setlCondition.endTime.substr(0, 4)

      if (yearL != yearR) {
        ElMessage({
          message: '请选择同一年份！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      if (setlCondition.selectType === 'first') {
        selectYbStatInfo(setlCondition)
          .then((res) => {
            setlinfos.value = res
          })
          .catch(() => {
            setlinfos.value = []
          })
      } else {
        selectYbStatRatio(setlCondition)
          .then((res) => {
            setlinfos.value = res
          })
          .catch(() => {
            setlinfos.value = []
          })
      }
    }

    const exportYbDetailExcel = () => {
      if (setldetails.value.length === 0) {
        ElMessage({
          message: '没有可以导出的数据！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
      } else {
        const title = {
          patNo: '住院号',
          times: '住院次数',
          psnCertType: '科室',
          psnName: '姓名',
          gendName: '性别',
          brdy: '出生日期',
          certno: '身份证',
          mainDiagnosis: '主要诊断',
          mainOperation: '主要手术',
          insuplcAdmdvsName: '参保地名称',
          insutypeName: '险种类型',
          medTypeName: '医疗类别',
          psnTypeName: '人员类别',
          mdtrtId: '就诊ID',
          setlId: '结算ID',
          begntime: '入院时间',
          endtime: '出院时间',
          setlTime: '结算时间',
          medfeeSumamt: '总医疗费用',
          fundPaySumamt: '总报销金额',
          mafPay: '医疗救助',
          acctPay: '个人账户支出',
          psnCashPay: '个人现金支出',
          hifmiPay: '大病支出',
          chargeWesternMedicine: '西药费',
          chargePatentMedicine: '中成药费',
          chargeHerbal: '中药饮片费',
          chargeSanitaryMaterial: '耗材费',
        }
        Export(setldetails.value, title, filterDialogTitle.value)
      }
    }

    const handleChange = (value) => {
    }

    const pageSize = ref(30)
    const currentPage = ref(1)
    const handleSizeChange = (val) => {
      pageSize.value = val
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    const selectChart = async () => {
      if (!dateRange.value) {
        ElMessage({
          message: '请选择时间范围！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      if (!setlCondition.dataInfo) {
        ElMessage({
          message: '请选择险种！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      setlCondition.setlType = setlCondition.dataInfo[0]
      setlCondition.insurType = setlCondition.dataInfo[1]

      setlCondition.startTime = formatDatetime(dateRange.value[0])
      setlCondition.endTime = formatDatetime(dateRange.value[1])

      let yearL = setlCondition.startTime.substr(0, 4)
      let yearR = setlCondition.endTime.substr(0, 4)

      if (yearL != yearR) {
        ElMessage({
          message: '请选择同一年份！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      qxtDrawer.value = true
      titleChart.value = yearL + '年医保收入分析图'

      let data = []
      data = await selectYbChart(setlCondition)
      let setlCondition1 = clone(setlCondition)
      setlCondition1.selectType = 'first'
      data = data.concat(await selectYbStatInfo(setlCondition1))
      chartData.value = data
    }

    watch(
      () => chartData.value,
      () => {
        let nameText
        let barTitles = ['总费用', '全部基金', '药品费', '耗材费']
        if (setlCondition.setlType === '21') {
          nameText = '住院'
        } else {
          nameText = '门诊'
        }
        nameText = titleChart.value + '(' + nameText + ')-'
        let yAxisName = '单位：百万元'
        let tipUnit = '元'

        let echartsXdata = []
        let zfy = []
        let zjj = []
        let ypf = []
        let clf = []
        let pieRc = []
        let pieZyts = []
        let pieZfy = []

        chartData.value.forEach((item) => {
          if (item.month) {
            zfy.push(item.zfy_jn)
            zjj.push(item.zjj_jn)
            if (item.ypf_jn > 0.0) {
              ypf.push(item.ypf_jn)
            }
            if (item.clf_jn > 0.0) {
              clf.push(item.clf_jn)
            }
            echartsXdata.push(item.month)
          } else {
            let dataRc = {}
            let dataZyts = {}
            let dataZfy = {}
            dataRc.value = item.psnCount
            dataRc.name = item.insurName
            dataRc.unit = '人'
            pieRc.push(dataRc)
            dataZyts.value = item.inDays
            dataZyts.name = item.insurName
            dataZyts.unit = '天'
            pieZyts.push(dataZyts)
            dataZfy.value = item.totalFee
            dataZfy.name = item.insurName
            dataZfy.unit = '元'
            pieZfy.push(dataZfy)
          }
        })
        barUtilsTwo(zfyDst, nameText + barTitles[0], echartsXdata, zfy, barTitles[0], yAxisName, tipUnit)
        barUtilsTwo(zjjDst, nameText + barTitles[1], echartsXdata, zjj, barTitles[1], yAxisName, tipUnit)
        barUtilsTwo(ypfDst, nameText + barTitles[2], echartsXdata, ypf, barTitles[2], yAxisName, tipUnit)
        barUtilsTwo(clfDst, nameText + barTitles[3], echartsXdata, clf, barTitles[3], yAxisName, tipUnit)

        pieUtilsOne(rcpie, '住院人次', pieRc)
        pieUtilsOne(zytsPie, '住院天数', pieZyts)
        pieUtilsOne(zfyPie, '总费用', pieZfy)
      }
    )

    const handleClick = (tab, event) => {
      if (!dateRange.value) {
        ElMessage({
          message: '请选择时间范围！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      if (!setlCondition.dataInfo) {
        ElMessage({
          message: '请选择险种！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }

      setlCondition.setlType = setlCondition.dataInfo[0]
      setlCondition.insurType = setlCondition.dataInfo[1]

      setlCondition.startTime = formatDatetime(dateRange.value[0])
      setlCondition.endTime = formatDatetime(dateRange.value[1])

      // 查询哪个tab页面
      setlCondition.selectType = tab.props.name

      if (setlCondition.selectType === 'first') {
        selectYbStatInfo(setlCondition)
          .then((res) => {
            setlinfos.value = res
          })
          .catch(() => {
            setlinfos.value = []
          })
      } else {
        selectYbStatRatio(setlCondition)
          .then((res) => {
            setlinfos.value = res
          })
          .catch(() => {
            setlinfos.value = []
          })
      }
    }

    const getSummaries = () => {
      if (setlCondition.selectType === 'first') {
        let sums1 = {
          insurName: '',
          psnCount: 0,
          inDays: 0,
          avgInDays: 0,
          totalFee: 0,
          drugFee: 0,
          drugFeeRatio: 0,
          matFee: 0,
          matFeeRatio: 0,
          fundPooling: 0,
          bigIllFundPooling: 0,
          civilServiceFund: 0,
          otherFunds: 0,
          allFunds: 0,
          acctPay: 0,
        }
        setlinfos.value.forEach((itm) => {
          for (let k in sums1) {
            sums1[k] = Number(sums1[k]) + Number(itm[k])
          }
        })
        sums1.insurName = '合计'
        sums1.avgInDays = (sums1.inDays / sums1.psnCount).toFixed(2)
        sums1.drugFeeRatio = ((sums1.drugFee / sums1.totalFee) * 100).toFixed(2)
        sums1.matFeeRatio = ((sums1.matFee / sums1.totalFee) * 100).toFixed(2)

        return sums1
      } else if (setlCondition.selectType === 'second') {
        let sums2 = {
          month: '',
          zfy_jn: 0,
          zfy_qn: 0,
          zfy_tb: 0,
          zjj_jn: 0,
          zjj_qn: 0,
          zjj_tb: 0,
          ypf_jn: 0,
          ypf_qn: 0,
          ypf_tb: 0,
          clf_jn: 0,
          clf_qn: 0,
          clf_tb: 0,
        }
        setlinfos.value.forEach((itm) => {
          for (let k in sums2) {
            sums2[k] = Number(sums2[k]) + Number(itm[k])
          }
        })
        sums2.month = '合计'
        sums2.zfy_tb = (((sums2.zfy_jn - sums2.zfy_qn) / sums2.zfy_qn) * 100).toFixed(2) + '%'
        sums2.zjj_tb = (((sums2.zjj_jn - sums2.zjj_qn) / sums2.zjj_qn) * 100).toFixed(2) + '%'
        sums2.ypf_tb = (((sums2.ypf_jn - sums2.ypf_qn) / sums2.ypf_qn) * 100).toFixed(2) + '%'
        sums2.clf_tb = (((sums2.clf_jn - sums2.clf_qn) / sums2.clf_qn) * 100).toFixed(2) + '%'
        return sums2
      } else {
        let sums3 = {
          month: '',
          zfy: 0,
          zfy_hb: 0,
          zjj: 0,
          zjj_hb: 0,
          ypf: 0,
          ypf_hb: 0,
          clf: 0,
          clf_hb: 0,
        }
        setlinfos.value.forEach((itm) => {
          for (let k in sums3) {
            sums3[k] = Number(sums3[k]) + Number(itm[k])
          }
        })
        sums3.month = '合计'
        sums3.zfy_hb = ''
        sums3.zjj_hb = ''
        sums3.ypf_hb = ''
        sums3.clf_hb = ''
        return sums3
      }
    }

    const getSummaries1 = (param) => {
      const { columns, data } = param
      const sums = []
      // 住院人次下标
      let psnCountIndex = 0
      // 住院天数下标
      let inDaysIndex = 0
      // 总费用下标
      let zfyIndex = 0
      // 药品费下标
      let ypfIndex = 0
      // 材料费下标
      let clfIndex = 0
      // 今年总费用下标
      let jn_zfy = 0
      // 去年总费用下标
      let qn_zfy = 0
      // 今年总基金下标
      let jn_zjj = 0
      // 去年总基金下标
      let qn_zjj = 0
      // 今年药品费下标
      let jn_ypf = 0
      // 去年药品费下标
      let qn_ypf = 0
      // 今年耗材费下标
      let jn_clf = 0
      // 去年耗材费下标
      let qn_clf = 0
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === 'psnCount') {
          psnCountIndex = index
        }
        if (column.property === 'inDays') {
          inDaysIndex = index
        }
        if (column.property === 'totalFee') {
          zfyIndex = index
        }
        if (column.property === 'drugFee') {
          ypfIndex = index
        }
        if (column.property === 'matFee') {
          clfIndex = index
        }
        if (column.property === 'jn_zfy') {
          jn_zfy = index
        }
        if (column.property === 'qn_zfy') {
          qn_zfy = index
        }
        if (column.property === 'jn_zjj') {
          jn_zjj = index
        }
        if (column.property === 'qn_zjj') {
          qn_zjj = index
        }
        if (column.property === 'jn_ypf') {
          jn_ypf = index
        }
        if (column.property === 'qn_ypf') {
          qn_ypf = index
        }
        if (column.property === 'jn_clf') {
          jn_clf = index
        }
        if (column.property === 'qn_clf') {
          qn_clf = index
        }
        const values = data.map((item) => Number(item[column.property]))
        if (column.property === 'avgInDays') {
          sums[index] = (sums[inDaysIndex] / sums[psnCountIndex]).toFixed(2)
        } else if (column.property === 'drugFeeRatio') {
          if (sums[zfyIndex] > 0) {
            sums[index] = ((sums[ypfIndex] / sums[zfyIndex]) * 100).toFixed(2)
          } else {
            sums[index] = 0.0
          }
        } else if (column.property === 'matFeeRatio') {
          if (sums[zfyIndex] > 0) {
            sums[index] = ((sums[clfIndex] / sums[zfyIndex]) * 100).toFixed(2)
          } else {
            sums[index] = 0.0
          }
        } else if (column.property === 'zfy_tb') {
          if (sums[qn_zfy] > 0) {
            sums[index] = (((sums[jn_zfy] - sums[qn_zfy]) / sums[qn_zfy]) * 100).toFixed(2) + '%'
          } else {
            sums[index] = 0.0 + '%'
          }
        } else if (column.property === 'zjj_tb') {
          if (sums[qn_zjj] > 0) {
            sums[index] = (((sums[jn_zjj] - sums[qn_zjj]) / sums[qn_zjj]) * 100).toFixed(2) + '%'
          } else {
            sums[index] = 0.0 + '%'
          }
        } else if (column.property === 'ypf_tb') {
          if (sums[qn_ypf] > 0) {
            sums[index] = (((sums[jn_ypf] - sums[qn_ypf]) / sums[qn_ypf]) * 100).toFixed(2) + '%'
          } else {
            sums[index] = 0.0 + '%'
          }
        } else if (column.property === 'clf_tb') {
          if (sums[qn_clf] > 0) {
            sums[index] = (((sums[jn_clf] - sums[qn_clf]) / sums[qn_clf]) * 100).toFixed(2) + '%'
          } else {
            sums[index] = 0.0 + '%'
          }
        } else if (column.property === 'zfy_hb') {
          sums[index] = ''
        } else if (column.property === 'zjj_hb') {
          sums[index] = ''
        } else if (column.property === 'ypf_hb') {
          sums[index] = ''
        } else if (column.property === 'clf_hb') {
          sums[index] = ''
        } else if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          //合计特殊处理
          if (column.property === 'psnCount' || column.property === 'inDays') {
            sums[index] = sums[index].toFixed(0)
          } else {
            sums[index] = sums[index].toFixed(2)
          }
        } else {
          sums[index] = 0
        }
      })

      sums.avgInDays = (sums.inDays / sums.psnCount).toFixed(2)
      sums.drugFeeRatio = ((sums.drugFee / sums.totalFee) * 100).toFixed(2)
      sums.matFeeRatio = ((sums.matFee / sums.totalFee) * 100).toFixed(2)

      return sums
    }

    const filterSetlTypeName = () => {
      if ('21' === setlCondition.setlType) {
        return setlCondition.options[0].label
      } else {
        return setlCondition.options[1].label
      }

      return ''
    }

    const filterInsurTypeName = () => {
      if ('21' === setlCondition.setlType) {
        for (let i = 0; i < setlCondition.options[0].children.length; i++) {
          if (setlCondition.options[0].children[i].value === setlCondition.insurType) {
            return setlCondition.options[0].children[i].label
          }
        }
      } else {
        for (let i = 0; i < setlCondition.options[1].children.length; i++) {
          if (setlCondition.options[1].children[i].value === setlCondition.insurType) {
            return setlCondition.options[1].children[i].label
          }
        }
      }

      return ''
    }

    const exportSetlinfoExcel = () => {
      let year = setlCondition.startTime.substr(0, 4) + '年'
      if (setlinfos.value.length === 0) {
        ElMessage({
          message: '没有可以导出的数据！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
      } else {
        const data = clone(setlinfos.value)
        data.push(getSummaries())

        // 增加导出正在进行中状态
        store.commit('app/setLoading', true)

        if (setlCondition.selectType === 'first') {
          const title = {
            insurName: '险种类型',
            psnCount: '住院人次',
            inDays: '住院天数',
            avgInDays: '平均住院日',
            totalFee: '总费用',
            drugFee: '药品费用',
            drugFeeRatio: '药品占比(%)',
            matFee: '耗材费用',
            matFeeRatio: '耗材占比(%)',
            fundPooling: '基本医疗统筹金额',
            bigIllFundPooling: '大病基金',
            civilServiceFund: '公务员基金支付',
            otherFunds: '其他基金',
            allFunds: '全部基金',
            acctPay: '个人账户支出',
          }
          const setlTypeName = filterSetlTypeName()
          const insurTypeName = filterInsurTypeName()
          Export(data, title, `【${year}】【${setlTypeName}】【${insurTypeName}】`)
        } else if (setlCondition.selectType === 'second') {
          const setlTypeName = filterSetlTypeName()
          const exportName = year + setlTypeName + '同比'
          if (setlinfos.value.length <= 0) {
            ElMessage({
              message: '没有可以导出的数据！',
              type: 'warning',
              duration: 2500,
              showClose: true,
            })
          }
          ElMessageBox.prompt('导出文件名字', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /\S/,
            inputErrorMessage: '文件名不能为空 (∩•̀ω•́)⊃-*⋆',
          })
            .then(({ value }) => {
              const data = {
                param: {
                  startTime: setlCondition.startTime,
                  endTime: setlCondition.endTime,
                  setlType: setlCondition.setlType,
                  insurType: setlCondition.insurType,
                  selectType: setlCondition.selectType,
                  exportName: exportName,
                },
                url: '/ybQuery/exportYbStatRatioExcel',
                fileName: value + '.xlsx',
              }
              setTimeout(() => {
                downloadExcel(data)
              }, 500)
            })
            .catch(() => {
            })
        } else {
          const setlTypeName = filterSetlTypeName()
          const exportName = year + setlTypeName + '环比'
          if (setlinfos.value.length <= 0) {
            ElMessage({
              message: '没有可以导出的数据！',
              type: 'warning',
              duration: 2500,
              showClose: true,
            })
          }
          ElMessageBox.prompt('导出文件名字', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /\S/,
            inputErrorMessage: '文件名不能为空 (∩•̀ω•́)⊃-*⋆',
          })
            .then(({ value }) => {
              const data = {
                param: {
                  startTime: setlCondition.startTime,
                  endTime: setlCondition.endTime,
                  setlType: setlCondition.setlType,
                  insurType: setlCondition.insurType,
                  selectType: setlCondition.selectType,
                  exportName: exportName,
                },
                url: '/ybQuery/exportYbStatRatioExcel',
                fileName: value + '.xlsx',
              }
              setTimeout(() => {
                downloadExcel(data)
              }, 500)
            })
            .catch(() => {
            })
        }
      }
    }

    const handleClose = (done) => {
      if (this.loading) {
        return
      }
      this.$confirm('确定要提交表单吗？')
        .then((_) => {
          this.loading = true
          this.timer = setTimeout(() => {
            done()
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false
            }, 400)
          }, 2000)
        })
        .catch((_) => {
        })
    }

    const cancelForm = () => {
      this.loading = false
      this.dialog = false
      clearTimeout(this.timer)
    }

    onMounted(() => {
      // 初始化数据
      setlCondition.selectType = 'first'
      deptNo.value = ''
    })

    const exportTreeRs = () => {
      let year = setlCondition.startTime.substr(0, 4) + '年'
      const setlTypeName = filterSetlTypeName()
      const exportName = year + setlTypeName + '人数'
      if (treeData.value.length <= 0) {
        ElMessage({
          message: '没有可以导出的数据！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
      }
      ElMessageBox.prompt('导出文件名字', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '文件名不能为空 (∩•̀ω•́)⊃-*⋆',
      })
        .then(({ value }) => {
          const data = {
            param: {
              startTime: setlCondition.startTime,
              endTime: setlCondition.endTime,
              setlType: setlCondition.setlType,
              selectType: setlCondition.selectType,
              dept: deptNo.value,
              doctor: doctorId.value,
              insurType: insurCode.value,
              exportName: exportName,
            },
            url: '/ybQuery/selectTreeAllData',
            fileName: value + '.xlsx',
          }
          setTimeout(() => {
            downloadExcel(data)
          }, 500)
        })
        .catch(() => {
        })
    }

    return {
      tableHeight,
      deptNo,
      doctorId,
      insurCode,
      dateRange,
      setlCondition,
      setlinfos,
      qxtDrawer,
      titleChart,
      chartData,
      pieChartData,
      showChart,
      treeChart,
      barChangeData,
      treeData,
      pageSize,
      currentPage,
      filterDialogTitle,
      setldetails,
      showSetldetails,
      showSetlinfoComponent,
      currentSetldetail,
      handleCurrentChange,
      handleSizeChange,
      fetchSetldetails,
      showBarChart,
      showTreeChart,
      selectTreeChart,
      exportTreeRs,
      selectChart,
      handleSelect,
      querySearchDept,
      querySearchDoctor,
      handleClose,
      cancelForm,
      getSummaries1,
      exportSetlinfoExcel,
      exportYbDetailExcel,
      handleChange,
      handleClick,
      openSetlinfoComponent,
      fetchSetlinfos,
    }
  },
}

function initInsurOptions() {
  return [
    {
      value: '21',
      label: '住院',
      children: [
        {
          value: 99,
          label: '全部',
        },
        {
          value: 43010031001,
          label: '长沙市城职',
        },
        {
          value: 43010039001,
          label: '长沙市城居',
        },
        {
          value: 43010034001,
          label: '长沙市离休',
        },
        {
          value: 43010051052,
          label: '长沙市生育',
        },
        {
          value: 43012131001,
          label: '长沙县城职',
        },
        {
          value: 43012139001,
          label: '长沙县城居',
        },
        {
          value: 43012134001,
          label: '长沙县离休',
        },
        {
          value: 43012151052,
          label: '长沙县生育',
        },
        {
          value: 43018131001,
          label: '浏阳市城职',
        },
        {
          value: 43018139001,
          label: '浏阳市城居',
        },
        {
          value: 43018134001,
          label: '浏阳市离休',
        },
        {
          value: 43018151052,
          label: '浏阳市生育',
        },
        {
          value: 43990031001,
          label: '湖南省城职',
        },
        {
          value: 43990034001,
          label: '湖南省离休',
        },
        {
          value: 43990051052,
          label: '湖南省生育',
        },
        {
          value: 43990001,
          label: '省内异地',
        },
        {
          value: 43990002,
          label: '省外异地',
        },
        {
          value: 4301002102,
          label: '市单病种',
        },
        {
          value: 4399002102,
          label: '省单病种',
        },
        {
          value: 4399012102,
          label: '省内单病种',
        },
      ],
    },
    {
      value: '11',
      label: '门诊',
      children: [
        {
          value: 99,
          label: '全部',
        },
        {
          value: 11,
          label: '普通门诊',
        },
        {
          value: 14,
          label: '特殊门诊',
        },
        {
          value: 51,
          label: '生育门诊',
        },
      ],
    },
  ]
}
</script>

<style scoped>
:deep(.el-table .children-row) {
  background: rgba(145, 247, 145, 0.5);
}

:deep(.el-table--border td:first-child .cell, .el-table--border th:first-child .cell) {
  padding-left: 4px;
}

:deep(.el-table) {
  --el-table-row-hover-background-color: #85dbfd7a;
}

:deep(.el-table__footer-wrapper tbody td) {
  background: #df4a25;
  color: white;
  font-weight: bold;
}

:deep(.el-main) {
  padding: 0 5px;
}

:deep(.el-dialog__header) {
  margin-right: 2px;
}
</style>
