<script lang="ts" setup name="PlanAdd">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { selectionListItem } from './environmentalList_interface'
import { SCHEDULE } from '@/utils/scheduleDict'
import { getenvironmentRecordAdd, getenvironmentRecordDetail, getenvironmentRecordUpdate } from '@/api/business/environmentRecord/environmentRecord'
import useUserStore from '@/store/modules/user'
const infoId = ref('') // id
const { name, id } = useUserStore()
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
} // 字典
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const formInline = ref({
  environmentCode: '', // 环境记录单编号
  roomNumber: '', // 房间编号
  recorder: name || '', // 用户名
  temperature: '', // 温度
  humidity: '', // 湿度
  outputVoltage: '', // 输出电压
  zeroGroundVoltage: '', // 零地电压
  remark: '', // 备注
  recordTime: dayjs(`${new Date()}`).format('YYYY-MM-DD hh:mm:ss'), // 记录时间
  createUser: id || '', // 记录人id
})
const addId = ref('') // 保存后的id
const ruleFormRef = ref<FormInstance>()

// 房间号模拟下拉框数据
const selectionList = ref<selectionListItem[]>([
  { label: '101', value: '101' },
  { label: '102', value: '102' },
  { label: '103', value: '103' },
  { label: '104', value: '104' },
])
// 校验规则
const rules = ref({
  roomNumber: [{ required: true, message: '房间号不能为空', trigger: ['blur', 'change'] }],
  recorder: [{ required: true, message: '记录人不能为空', trigger: ['blur', 'change'] }],
  recordTime: [{ required: true, message: '记录时间不能为空', trigger: ['blur', 'change'] }],
  humidity: [{ required: true, message: '湿度(%)不能为空', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '湿度(%)只能为数字', trigger: ['blur', 'change'] },
  ],
  temperature: [{ required: true, message: '温度(℃)不能为空', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '温度(℃)只能为数字', trigger: ['blur', 'change'] },
  ],
  outputVoltage: [{ required: true, message: '输出电压(V)不能为空', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '输出电压(V)只能为数字', trigger: ['blur', 'change'] },
  ],
  zeroGroundVoltage: [{ required: true, message: '零地电压(V)不能为空', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '零地电压(V)只能为数字', trigger: ['blur', 'change'] },
  ],
}) // 表单验证规则

// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// if (infoId.value && infoId.value !== '') {
//   getenvironmentRecordDetail({ id: infoId.value }).then((res) => {
//     formInline.value = res.data
//   })
// }
// 点击保存
const preserve = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm('确认提交吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (pageType.value === 'add') {
          // getenvironmentRecordAdd(formInline.value).then((res) => {
        //   if (res.code === 200) {
        //     addId.value = res.data.id
        //     ElMessage.success('保存成功！')
        //   }
        // })
        }
        else {
          // getenvironmentRecordUpdate(formInline.value).then((res) => {
        //   if (res.code === 200) {
        //     addId.value = res.data.id
        //     ElMessage.success('保存成功！')
        //   }
        // })
        }
      })
    }
  })
}
// 打印
const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '环境记录单模板', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
</script>

<template>
  <app-container>
    <detail-page :title="`环境记录单-${textMap[pageType]}`">
      <template #btns>
        <el-button
          v-if="pageType !== 'detail'"
          type="primary"
          @click="
            preserve(ruleFormRef)
          "
        >
          提交
        </el-button>
        <el-button v-else v-print="printObj" type="primary">
          打印
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        id="form"
        ref="ruleFormRef"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
        label-width="auto"
        label-position="right"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="记录单号:">
              <el-input
                v-model="formInline.environmentCode"
                :placeholder="pageType === 'detail' ? '无' : '系统自动生成'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="房间号:" prop="roomNumber">
              <el-select
                v-model="formInline.roomNumber"
                clearable
                filterable
                :placeholder="pageType === 'detail' ? '无' : '请选择房间号'"
                size="default"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="item in selectionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="记录人:" prop="recorder">
              <el-input
                v-model="formInline.recorder"
                :placeholder="pageType === 'detail' ? '无' : '请输入记录人'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="记录时间:" prop="recordTime">
              <el-date-picker
                v-model="formInline.recordTime"
                type="datetime"
                :placeholder="pageType === 'detail' ? '无' : '请选择记录时间'"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                clearable
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="温度(℃):" prop="temperature">
              <el-input
                v-model="formInline.temperature"
                :placeholder="pageType === 'detail' ? '无' : '请输入温度(℃)'"
                :disabled="pageType === 'detail'"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="湿度(%):" prop="humidity">
              <el-input
                v-model="formInline.humidity"
                :placeholder="pageType === 'detail' ? '无' : '请输入湿度(%)'"
                :disabled="pageType === 'detail'"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="输出电压(V):" prop="outputVoltage">
              <el-input
                v-model="formInline.outputVoltage"
                :placeholder="pageType === 'detail' ? '无' : '请输入输出电压(V)'"
                :disabled="pageType === 'detail'"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="零地电压(V):" prop="zeroGroundVoltage">
              <el-input
                v-model="formInline.zeroGroundVoltage"
                :placeholder="pageType === 'detail' ? '无' : '请输入零地电压(V)'"
                :disabled="pageType === 'detail'"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
  </app-container>
</template>
