<!-- 环境记录单设置 -->
<script name="EnvironmentSetting" lang="ts" setup>
import { ElMessage } from 'element-plus'
import { createEditor } from '@wangeditor/editor'
import type { IEvnConfig, IListQuery, ILocation } from './record-interface'
import { batchAddConfig, delEnvConfig, getEnvConfigList } from '@/api/resource/environment'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'

const router = useRouter()

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

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

const envConfigList = ref<Array<IEvnConfig>>([])

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

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

const configRecord: IEvnConfig = {
  locationId: '',
  locationName: '',
  recordTimeList: [],
  editable: true,
  pickTime1: '',
  pickTime2: '',
  pickTime3: '',
  pickTime4: '',
}

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

const initEnvConfig = () => {
  getEnvConfigList(listQuery).then((res) => {
    if (res.code === 200) {
      envConfigList.value = res.data.map((item: IEvnConfig) => {
        return {
          ...item,
          recordTimeListStr: item.recordTimeList.toString().replaceAll(',', '\t/\t'),
          pickTime1: item.recordTimeList.length > 0 ? item.recordTimeList[0] : '',
          pickTime2: item.recordTimeList.length > 1 ? item.recordTimeList[1] : '',
          pickTime3: item.recordTimeList.length > 2 ? item.recordTimeList[2] : '',
          pickTime4: item.recordTimeList.length > 3 ? item.recordTimeList[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 jointRecordTime = (obj: IEvnConfig) => {
  if (obj.editable === true) {
    const arr = ref<Array<string>>([])
    if (obj.pickTime1 !== '') { arr.value.push(obj.pickTime1!) }
    if (obj.pickTime2 !== '') { arr.value.push(obj.pickTime2!) }
    if (obj.pickTime3 !== '') { arr.value.push(obj.pickTime3!) }
    if (obj.pickTime4 !== '') { arr.value.push(obj.pickTime4!) }

    return arr
  }
  else {
    return obj.recordTimeList
  }
}

const jointRecordTimeStr = (obj: IEvnConfig) => {
  if (obj.editable === true) {
    const str = ref<string>('')
    if (obj.pickTime1 !== '') { str.value += obj.pickTime1 }
    if (obj.pickTime2 !== '') { str.value += obj.pickTime2 }
    if (obj.pickTime3 !== '') { str.value += obj.pickTime3 }
    if (obj.pickTime4 !== '') { str.value += obj.pickTime4 }

    return str
  }
  else {
    return obj.recordTimeList.toString().replaceAll(',', '\t/\t')
  }
}

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

  //
  envConfigList.value = envConfigList.value.map((item: any) => ({
    ...item,
    locationName: getLocationNameById(locationList.value, item.locationId),
    recordTimeList: jointRecordTime(item),
    recordTimeListStr: jointRecordTimeStr(item),
  }))

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

const saveForm = () => {
  envConfigList.value = envConfigList.value.map((item: any) => ({
    ...item,
    locationName: getLocationNameById(locationList.value, item.locationId),
    recordTimeList: jointRecordTime(item),
    recordTimeListStr: jointRecordTimeStr(item),
  }))

  // 校验数据
  if (useCheckList(envConfigList.value, configColumns, '配置项')) {
    // 筛选需要保存的记录
    const configToSave = ref<Array<IEvnConfig>>([])
    configToSave.value = envConfigList.value.filter((item) => { return item.editable === true })

    // 批量保存
    batchAddConfig(configToSave.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('环境记录单配置保存成功')
        initEnvConfig()
      }
      else {
        ElMessage.error(`环境记录单配置项保存失败：${res.message}`)
      }
    })
  }
}

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

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

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

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

    initEnvConfig()
  }
}

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

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="请选择记录地点">
                <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 === 'recordTimeListStr'">
                <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>
