Newer
Older
xc-metering-front / src / views / laboratory / statement / environment / detail.vue
dutingting on 23 Nov 2023 8 KB 环境记录单
<!-- 环境记录单设置 -->
<script name="EnvironmentSetting" lang="ts" setup>
import { ElLoading, ElMessage } from 'element-plus'
import { createEditor } from '@wangeditor/editor'
import { ITEM_RENDER_EVT } from 'element-plus/es/components/virtual-list/src/defaults'
import type { IEvnConfig, IListQuery, ILocation } from './environment-interface'
// import { batchAddConfig, delEnvConfig, getEnvConfigList } from '@/api/resource/environment'
import { useCheckList } from '@/utils/useCheckList'
import { useSetAllRowReadable } from '@/utils/useSetAllRowReadable'
import { addEnvironmentList, deleteEnvironment, getEnvironmentDetail } from '@/api/laboratory/environment'

const router = useRouter()

const listQuery = {
  locationId: '',
  limit: 1000,
  offset: 1,
}

const configColumns = [
  { text: '记录地点', value: 'locationName', align: 'center', required: true, width: '300' },
  { text: '记录时间', value: 'recordTime', align: 'center', required: true },
] as any // 表头

const envConfigList = ref([]) as any

// 表格被选中的行
const locationSelected = ref<IEvnConfig[]>([])

const locationList = ref<Array<ILocation>>([])

const configRecord: IEvnConfig = {
  locationId: '', // 地点id
  locationName: '',
  recordTimeList: [],
  editable: true,
  pickTime1: '',
  pickTime2: '',
  pickTime3: '',
  pickTime4: '',
  recordTime: '', // 记录时间
}

// 逻辑
const resetForm = () => {
  router.go(-1)
}

// 获取记录单列表
const initEnvConfig = () => {
  getEnvironmentDetail(listQuery).then((res) => {
    if (res.code === 200 && Array.isArray(res.data.rows)) {
      envConfigList.value = res.data.rows.map((item: IEvnConfig) => {
        return {
          ...item,
          recordTime: item.recordTime.replaceAll(',', '\t/\t'),
          pickTime1: item.recordTime.split(',').length > 0 ? item.recordTime.split(',')[0] : '',
          pickTime2: item.recordTime.split(',').length > 1 ? item.recordTime.split(',')[1] : '',
          pickTime3: item.recordTime.split(',').length > 2 ? item.recordTime.split(',')[2] : '',
          pickTime4: item.recordTime.split(',').length > 3 ? item.recordTime.split(',')[3] : '',
        }
      })
    }
  })
}

const containsLocation = (list: Array<IEvnConfig>, location: string) => {
  const target = list.filter(item => item.locationId === location)
  return target.length !== 0
}

const getLocationNameById = (list: Array<ILocation>, locationId: string) => {
  const target = list.filter(item => item.id === locationId)
  if (target.length > 0) {
    return target.at(0)?.locationName
  }
  else {
    return ''
  }
}

// 增加行
const addEditableRow = () => {
  // 判断是否已经有选择过的地点
  locationList.value = locationList.value.map(opts => ({
    ...opts,
    disabled: containsLocation(envConfigList.value, opts.id),
  }))

  envConfigList.value = envConfigList.value.map((item: any) => ({
    ...item,
    recordTime: [item.pickTime1, item.pickTime2, item.pickTime3, item.pickTime4].filter(item => item).join(','),
  }))
  console.log(envConfigList.value)

  if (useCheckList(envConfigList.value, configColumns, '配置项')) {
    // useSetAllRowReadable(envConfigList.value)
    envConfigList.value.push({ ...configRecord })
  }
}

async function saveForm() {
  console.log(envConfigList.value)
  envConfigList.value = envConfigList.value.map((item: any) => ({
    ...item,
    recordTime: [item.pickTime1, item.pickTime2, item.pickTime3, item.pickTime4].filter(item => item).join(','),
  }))

  // 校验数据
  if (useCheckList(envConfigList.value, configColumns, '配置项')) {
    // 筛选需要保存的记录
    const configToSave = ref<Array<IEvnConfig>>([])
    configToSave.value = envConfigList.value.filter((item: any) => { return item.editable === true })
    if (configToSave.value.length) {
      let recDeleted = 0
      const loading = ElLoading.service({})
      await Promise.all(configToSave.value.map(async (item) => {
        await addEnvironmentList(item).then((res) => {
          if (res.code !== 200) {
            ElMessage.error(`环境记录单配置项保存失败:${res.message}`)
            loading.close()
          }
          else {
            recDeleted++
          }
        })
      }))

      if (recDeleted === configToSave.value.length) {
        ElMessage.success('环境记录单配置项保存成功')
        loading.close()
      }

      initEnvConfig()
    }
  }
}

const delConfigByLocation = async () => {
  if (locationSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

  // 前端界面删除
  envConfigList.value = envConfigList.value.filter((item: any) => locationSelected.value.includes(item) === false)

  // 逐个调用后端接口进行删除
  const locationIdsSelected = ref<string[]>([])
  locationIdsSelected.value = locationSelected.value.map((item: any) => item.id)
  locationIdsSelected.value = locationIdsSelected.value.filter(item => item !== '')
  if (locationIdsSelected.value.length > 0) {
    let recDeleted = 0
    const loading = ElLoading.service({})
    await Promise.all(locationIdsSelected.value.map(async (id) => {
      await deleteEnvironment({ id }).then((res) => {
        if (res.code !== 200) {
          ElMessage.error(`删除环境记录单配置失败:${res.message}`)
          loading.close()
        }
        else {
          recDeleted++
        }
      })
    }))

    if (recDeleted === locationIdsSelected.value.length) {
      ElMessage.success('删除环境记录单配置成功')
      loading.close()
    }

    initEnvConfig()
  }
}

const locationMultiSelect = (e: any) => {
  locationSelected.value = e
}

// 选择地点变化
const changeSelectLocation = (val: string, row: any) => {
  const index = locationList.value.findIndex(item => item.id === val)
  if (index !== -1) {
    row.locationName = locationList.value[index].locationName
  }
}

onMounted(() => {
  initEnvConfig()
  locationList.value = JSON.parse(sessionStorage.getItem('envlocationList')!)
})
</script>

<template>
  <app-container>
    <detail-page title="环境记录单(设置)" style="margin-bottom: 20px;">
      <template #btns>
        <el-button type="primary" @click="saveForm()">
          保存
        </el-button>
        <el-button type="info" @click="resetForm()">
          关闭
        </el-button>
      </template>
    </detail-page>

    <el-form ref="configFormRef" label-position="right" label-width="110px" border stripe>
      <table-container title="">
        <template #btns-right>
          <el-button type="primary" @click="addEditableRow">
            增加行
          </el-button>
          <el-button type="info" @click="delConfigByLocation">
            删除行
          </el-button>
        </template>

        <!-- 表格区域 -->
        <el-table :data="envConfigList" border style="width: 100%;" @selection-change="locationMultiSelect">
          <el-table-column type="selection" align="center" width="38" />
          <el-table-column align="center" label="序号" width="55" type="index" />
          <el-table-column
            v-for="item in configColumns"
            :key="item.value"
            :prop="item.value"
            :label="item.text"
            :width="item.width"
            align="center"
          >
            <template #header>
              <span>{{ item.text }}</span>
            </template>
            <template #default="scope">
              <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>

              <el-select v-else-if="item.value === 'locationName'" v-model="scope.row.locationId" style="width: 100%;" placeholder="请选择记录地点" @change="(val) => changeSelectLocation(val, scope.row)">
                <el-option v-for="loca in locationList" :key="loca.id" :label="loca.locationName" :value="loca.id" :disabled="loca.disabled" />
              </el-select>

              <template v-else-if="item.value === 'recordTime'">
                <el-time-picker v-model="scope.row.pickTime1" style="width: 25%; padding: 0 5px;" value-format="HH:mm:ss" :default-value="new Date(0, 0, 0, 8, 0, 0)" />
                <el-time-picker v-model="scope.row.pickTime2" style="width: 25%; padding: 0 5px;" value-format="HH:mm:ss" :default-value="new Date(0, 0, 0, 10, 0, 0)" />
                <el-time-picker v-model="scope.row.pickTime3" style="width: 25%; padding: 0 5px;" value-format="HH:mm:ss" :default-value="new Date(0, 0, 0, 14, 0, 0)" />
                <el-time-picker v-model="scope.row.pickTime4" style="width: 25%; padding: 0 5px;" value-format="HH:mm:ss" :default-value="new Date(0, 0, 0, 16, 0, 0)" />
              </template>

              <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
            </template>
          </el-table-column>
        </el-table>
      </table-container>
    </el-form>
  </app-container>
</template>