<template>
  <el-container>
    <page-layer>
      <template #header>
        <span style="margin-left: 0">日期范围：</span>
        <el-date-picker
            v-model="requestParam.datePeriod"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
            style="width: 240px"
        ></el-date-picker>
        <el-button type="primary" style="margin-left: 30px" icon="Search" @click="queryStockIndex"> 查询</el-button>
        <el-button type="primary" icon="Upload" @click="saveSelections"> 保存</el-button>
        <span style="margin-left: 30px">检索</span>
        <el-input v-model="requestParam.search" placeholder="输入药品编码，多个编码之间以英文逗号分隔" clearable
                  style="width: 360px; margin-left: 10px"></el-input>
      </template>
      <template #aside>
        <el-table :data="data.stockIndex" :row-class-name="addIndexToRow" highlight-current-row
                  @row-click="mkGetDetailParam">
          <el-table-column prop="drawNo" label="盘点单号" width="100"></el-table-column>
          <el-table-column prop="outDate" label="盘点日期"></el-table-column>
        </el-table>
      </template>
      <template #main>
            <el-table :data="computedList.slice((currentPage - 1) * pageSize, currentPage * pageSize)" stripe
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="chargeCode" label="编码" sortable></el-table-column>
              <el-table-column prop="name" label="名称"></el-table-column>
              <el-table-column prop="serial" label="包装规格"></el-table-column>
              <el-table-column prop="lastCurrStockAmount" label="上期存量">
                <template v-slot="scope">
                  <el-input v-model="scope.row.lastCurrStockAmount" :style="colorText(scope.row)"
                            :disabled="!scope.row.editable"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="lastStockAmountInTheory" label="上期理论存量">
                <template v-slot="scope">
                  <span style="color: green; font-weight: bold">{{ scope.row.lastStockAmountInTheory }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="inYf" label="本期入库量"></el-table-column>
              <el-table-column prop="amount4" label="本期出库量"></el-table-column>
              <el-table-column label="本期账存量">
                <template v-slot="scope">
                  <el-input v-model="scope.row.stockAmount" type="number" :disabled="!scope.row.editable2"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="本期实盘量">
                <template v-slot="scope">
                  <el-input v-model="scope.row.currStockAmount" type="number"
                            :disabled="!scope.row.editable2"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="amount1" label="本期住院医嘱用量"></el-table-column>
              <el-table-column prop="amount2" label="本期医技记账数量"></el-table-column>
              <el-table-column prop="amount3" label="本期急诊转录数量"></el-table-column>
              <el-table-column prop="zyTotal" label="本期住院总用量"></el-table-column>
              <el-table-column prop="diff1" sortable label="出库与医嘱用量差异">
                <template v-slot="scope">
                  <span :style="colorText(scope.row.diff1)">{{ scope.row.diff1 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="diff2" sortable label="出库与住院差异">
                <template v-slot="scope">
                  <span :style="colorText(scope.row.diff2)">{{ scope.row.diff2 }}</span>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin: 5px 10px">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[15, 30, 45, 60]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  background
                  :total="computedList.length"
              >
              </el-pagination>
            </div>
      </template>
    </page-layer>
  </el-container>
</template>

<script>
import {computed, onMounted, reactive, ref} from 'vue'
import store from '@/store'
import {formatDate} from '@/utils/date'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getStockIndex, getStockDetail, saveStockChanges} from '@/api/reports/medicine-stock-count'
import {shortcuts} from '@/data/shortcuts'
import PageLayer from "@/layout/PageLayer";

export default {
  components: {PageLayer},
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 85
    const requestParam = reactive({datePeriod: [], start: '', end: '', search: ''})
    const queryDetailParam = reactive({
      start: '',
      end: '',
      drawNo: '',
      lastDrawNo: '',
      selections: [],
    })
    onMounted(() => {
      const tDate = new Date()
      const start = tDate.getFullYear() - 1 + '-01-01'
      const end = tDate.getFullYear() + '-' + (tDate.getMonth() + 1) + '-' + tDate.getDate()
      requestParam.start = start
      requestParam.end = end
      requestParam.datePeriod = [start, end]
    })

    const data = reactive({stockIndex: [], list: []})
    const computedList = computed(() => {
      if (requestParam.search === '') {
        return data.list
      } else {
        return data.list.filter((item) => {
          let searches = requestParam.search.split(',')
          if (searches.indexOf(item.chargeCode.trim()) !== -1) {
            return item
          }
        })
      }
    })
    const addIndexToRow = ({row, rowIndex}) => {
      row.index = rowIndex
    }
    const currentPage = ref(1)
    const pageSize = ref(15)
    const handleSizeChange = (val) => {
      pageSize.value = val
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }
    const queryStockIndex = () => {
      requestParam.start = formatDate(requestParam.datePeriod[0])
      requestParam.end = formatDate(requestParam.datePeriod[1])
      getStockIndex(requestParam).then((res) => (data.stockIndex = res))
    }
    const mkGetDetailParam = (row) => {
      queryDetailParam.drawNo = row.drawNo
      queryDetailParam.end = row.outDate
      if (row.index === 0) {
        queryDetailParam.lastDrawNo = ''
        ElMessageBox.prompt('请输入上一次盘点日期（例：2020-01-01）', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: '',
          inputPattern:
              /((?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29)/,
          inputErrorMessage: '日期格式不正确',
        }).then(({value}) => {
          queryDetailParam.start = value
          getStockDetail(queryDetailParam).then((res) => (data.list = res))
        })
      } else {
        queryDetailParam.lastDrawNo = data.stockIndex[row.index - 1].drawNo
        queryDetailParam.start = data.stockIndex[row.index - 1].outDate
        getStockDetail(queryDetailParam).then((res) => (data.list = res))
      }
    }
    const handleSelectionChange = (val) => {
      queryDetailParam.selections.forEach((item) => {
        item.editable = false
        item.editable2 = false
      })
      val.forEach((item) => {
        item.editable2 = true
        if (item.lastCurrStockAmount !== '无') item.editable = true
      })
      queryDetailParam.selections = val
    }
    const saveSelections = () => {
      if (queryDetailParam.selections.length === 0) {
        ElMessage({
          type: 'warning',
          message: '没有更改，无需保存',
          duration: 3000,
          showClose: true,
        })
      } else {
        const confirmText =
            '<p>本期盘点单号：' +
            queryDetailParam.selections[0].drawNo +
            '</p>' +
            '<p>上期盘点单号：' +
            queryDetailParam.lastDrawNo +
            '</p>' +
            '<p>请确认上述单号无误，是否继续保存？</p>'
        ElMessageBox.confirm(confirmText, '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
            .then(() => {
              saveStockChanges(queryDetailParam).then(() => {
                ElMessage({
                  type: 'success',
                  message: '保存成功',
                  duration: 3000,
                  showClose: true,
                })
              })
            })
            .catch(() => {
            })
      }
    }
    const colorText = (val) => {
      let color = ''
      if (val && val.chargeCode) {
        if (val.lastCurrStockAmount === '无') {
          color = 'gray'
        } else {
          color = Number(val.lastCurrStockAmount) - Number(val.lastStockAmountInTheory) === 0 ? 'green' : 'red'
        }
      } else {
        color = val === 0 ? 'green' : 'red'
      }
      return {
        color: color,
        fontWeight: 'bold',
      }
    }
    return {
      windowSize,
      tableHeight,
      requestParam,
      shortcuts,
      data,
      addIndexToRow,
      queryStockIndex,
      computedList,
      currentPage,
      pageSize,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      mkGetDetailParam,
      colorText,
      saveSelections,
    }
  },
}
</script>
