<template>
  <el-container>
    <el-header style="height: 35px; margin-top: 10px">
      <el-date-picker v-model="setlCondition.month" :clearable="false" placeholder="请选择" style="width: 110px"
        type="month"></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="el-icon-search" type="success" @click="fetchSetlinfos">查询</el-button>
      <el-button icon="el-icon-download" type="primary" @click="exportSetlinfoExcel">导出Excel</el-button>
    </el-header>
    <el-main>
      <el-table :data="setlinfos" :max-height="tableHeight" border highlight-current-row row-key="childKey" show-summary
        :summary-method="getSummaries1">
        <el-table-column label="险种类型" prop="insurName" header-align="center"></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>
      <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-main>
  </el-container>
</template>

<script>
import { computed, onMounted, reactive, ref } from 'vue'
import { formatMonth } from '@/utils/date'
import { useStore } from 'vuex'
import {
  selectYbStatInfo
} from '@/api/medical-insurance/si-ybkf'
import { clone } from '@/utils/clone'
import { Export } from '@/utils/ExportExcel'
import { ElMessage } from 'element-plus'

export default {
  components: {

  },
  setup() {
    const store = useStore()
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 55

    const setlCondition = reactive({
      month: formatMonth(new Date()),
      setlType: '21',
      insurType: null,
      dataInfo: null,
      options: initInsurOptions(),
    })

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

    const admdvsNameStyle = (children, isChildren) => {
      return {
        position: 'absolute',
        top: '6px',
        left: children || isChildren ? '24px' : '10px',
        width: '110px',
      }
    }

    const fetchSetlinfos = () => {
      if (!setlCondition.month) {
        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.month = formatMonth(setlCondition.month)
      selectYbStatInfo(setlCondition)
        .then((res) => {
          setlinfos.value = res
        })
        .catch(() => {
          setlinfos.value = []
        })
    }

    const handleChange = (value) => {
      console.log(value);
    }

    const getSummaries = () => {
      let sums = {
        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,
      }
      setlinfos.value.forEach((itm) => {
        for (let k in sums) {
          sums[k] = Number(sums[k]) + Number(itm[k])
        }
      })
      sums.insurName = '合计'
      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 getSummaries1 = (param) => {
      const { columns, data } = param
      const sums = []
      // 住院人次下标
      let psnCountIndex = 0
      // 住院天数下标
      let inDaysIndex = 0
      // 总费用下标
      let zfyIndex = 0
      // 药品费下标
      let ypfIndex = 0
      // 材料费下标
      let clfIndex = 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
        }
        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.00
          }
        } else if (column.property === 'matFeeRatio') {
          if (sums[zfyIndex] > 0) {
            sums[index] = (sums[clfIndex] / sums[zfyIndex] * 100).toFixed(2)
          } else {
            sums[index] = 0.00
          }
        } 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 = () => {
      if (setlinfos.value.length === 0) {
        ElMessage({
          message: '没有可以导出的数据！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
      } else {
        const data = clone(setlinfos.value)
        data.push(getSummaries())
        const title = {
          insurName: '险种类型',
          psnCount: '住院人次',
          inDays: '住院天数',
          avgInDays: '平均住院日',
          totalFee: '总费用',
          drugFee: '药品费用',
          drugFeeRatio: '药品占比(%)',
          matFee: '耗材费用',
          matFeeRatio: '耗材占比(%)',
          fundPooling: '基本医疗统筹金额',
          bigIllFundPooling: '大病基金',
          civilServiceFund: '公务员基金支付',
          otherFunds: '其他基金',
          allFunds: '全部基金',
        }
        const setlTypeName = filterSetlTypeName()
        const insurTypeName = filterInsurTypeName()
        Export(data, title, `【${setlCondition.month}】【${setlTypeName}】【${insurTypeName}】`)
      }
    }

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

    onMounted(() => {

    })

    return {
      tableHeight,
      setlCondition,
      setlinfos,
      setldetails,
      showSetldetails,
      pageSize,
      currentPage,
      getSummaries1,
      exportSetlinfoExcel,
      handleChange,
      admdvsNameStyle,
      handleCurrentChange,
      handleSizeChange,
      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: 3,
          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;
}
</style>
