<template>
  <my-layout>
    <el-card class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" @submit.stop.prevent>
        <el-form-item label="关键词">
          <el-input v-model="state.filter.keyWord" placeholder="描述" @keyup.enter="onQuery" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="state.filter.stDate"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="state.filter.edDate"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
          <el-button v-auth="'api:admin:item-def-bag:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <el-table
        :data="state.bagListData"
        style="width: 100%"
        v-loading="state.loading"
        border
      >
        <el-table-column prop="itemDescription" label="描述" min-width="180" show-overflow-tooltip />
        <el-table-column label="型号" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getModelName(row.model) }}
          </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容量(g)" min-width="120" show-overflow-tooltip />
        <el-table-column prop="tareWeight" label="皮重(g)" min-width="120" show-overflow-tooltip />
        <el-table-column prop="lowerLimitVolume" label="下限体积(g)" min-width="120" show-overflow-tooltip />
        <el-table-column prop="residualVolume" label="残余量(g)" min-width="120" show-overflow-tooltip />
        <el-table-column label="状态" width="80" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="success" v-if="row.status">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" :formatter="formatterTime" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button
              v-if="auth('api:admin:item-def-bag:update')"
              icon="ele-EditPen"
              size="small"
              text
              type="primary"
              @click="onEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="auth('api:admin:item-def-bag:soft-delete')"
              icon="ele-Delete"
              size="small"
              text
              type="danger"
              @click="onDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination
          v-model:currentPage="state.pageInput.currentPage"
          v-model:page-size="state.pageInput.pageSize"
          :total="state.total"
          :page-sizes="[10, 20, 50, 100]"
          size="small"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <liquid-bag-form ref="liquidBagFormRef" :title="state.formTitle"></liquid-bag-form>
  </my-layout>
</template>

<script lang="ts" setup name="admin/liquidbag">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { BagDto, PageInputBagDtoGetPageInput } from '/@/api/admin/data-contracts'
import { ItemDefBagApi } from '/@/api/admin/item-def-bag'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import dayjs from 'dayjs'
import { BagModelEnum } from '/@/api/admin/data-contracts'
import { DictApi } from '/@/api/admin/Dict'

const LiquidBagForm = defineAsyncComponent(() => import('./components/liquid-bag-form.vue'))

const { proxy } = getCurrentInstance() as any

const liquidBagFormRef = ref()

const state = reactive({
  loading: false,
  formTitle: '',
  filter: {
    keyWord: '',
    stDate: '',
    edDate: ''
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    filter: {
      keyWord: '',
      stDate: '',
      edDate: ''
    },
  } as PageInputBagDtoGetPageInput,
  bagListData: [] as Array<BagDto>,
  modelOptions: [] as BagModelEnum[],
})

onMounted(async () => {
  getModelOptions()
  onQuery()
  eventBus.on('refreshLiquidBag', () => {
    onQuery()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshLiquidBag')
})

const formatterTime = (row: any, column: any, cellValue: any) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : ''
}

const getModelOptions = async () => {
  const res = await new DictApi().getList(['bag_model'])
  if (res?.data?.bag_model) {
    state.modelOptions = res.data.bag_model.map((item: any) => ({
      value: Number(item.value) || 1,
      label: item.name || '',
    }))
  }
}

const onQuery = async () => {
  state.loading = true
  if (state.pageInput.filter) {
    state.pageInput.filter.keyWord = state.filter.keyWord
    state.pageInput.filter.stDate = state.filter.stDate || null
    state.pageInput.filter.edDate = state.filter.edDate
  }
  const res = await new ItemDefBagApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })
  state.bagListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}

const onAdd = () => {
  state.formTitle = '新增液袋'
  liquidBagFormRef.value.open()
}

const onEdit = (row: BagDto) => {
  state.formTitle = '编辑液袋'
  liquidBagFormRef.value.open(row)
}

const onDelete = (row: BagDto) => {
  proxy.$modal
    .confirmDelete(`确定要删除项目【${row.itemDescription}】?`)
    .then(async () => {
      await new ItemDefBagApi().softDelete({ id: row.id }, { loading: true })
      onQuery()
    })
    .catch(() => {})
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}

const getModelName = (modelValue: number) => {
  const model = state.modelOptions.find(item => item.value === modelValue)
  return model ? model.label : modelValue
}
</script>

<style scoped lang="scss"></style>