<template>
  <el-row :gutter="20">
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <!-- 筛选表单 -->
      <ContentWrap style="border: 0">
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="工序" prop="process">
            <el-input
              v-model="queryParams.process"
              placeholder="请输入工序"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="步骤分解" prop="stepBreak">
            <el-input
              v-model="queryParams.stepBreak"
              placeholder="请输入步骤分解"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="环境因素" prop="environmentElement">
            <el-input
              v-model="queryParams.environmentElement"
              placeholder="请输入环境因素"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" />搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" />重置
            </el-button>
            <el-button type="primary" @click="openAddDialog" color="#626aef"
              ><Icon icon="ep:plus" class="mr-5px" />新增</el-button
            >
            <el-button type="success" plain @click="handleExport" :loading="exportLoading">
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 表格 -->
      <ContentWrap style="border: 0">
        <zm-table :data="tableData" height="66vh">
          <zm-table-column label="序号" width="70" align="center" fixed="left">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>
          <zm-table-column
            label="工序"
            prop="process"
            align="center"
            fixed="left"
            min-width="150" />
          <zm-table-column label="步骤分解" min-width="150" prop="stepBreak" align="center" />
          <zm-table-column label="环境因素" prop="environmentElement" align="center" />

          <zm-table-column label="时态" align="center">
            <zm-table-column label="过去" prop="timeBefore" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.timeBefore">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="现在" prop="timeNow" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.timeNow">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="将来" prop="timeFuture" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.timeFuture">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
          </zm-table-column>

          <zm-table-column label="状态" align="center">
            <zm-table-column label="正常" prop="statusNormal" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.statusNormal">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="异常" prop="statusException" width="60" align="center">
              <template #default="{ row }">
                <el-button
                  circle
                  type="success"
                  style="border: none"
                  plain
                  v-if="row.statusException">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="紧急" prop="statusDanger" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.statusDanger">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
          </zm-table-column>

          <zm-table-column label="环境影响类型" align="center">
            <zm-table-column label="能源/资源耗用" prop="typeEnergy" align="center">
              <template #default="{ row }">
                <!-- <span>
                {{ row.typeEnergy ? '✔' : '' }}
              </span> -->

                <el-button circle type="success" style="border: none" plain v-if="row.typeEnergy">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="水体" prop="typeWater" width="60" align="center">
              <template #default="{ row }">
                <!-- <span>
                {{ row.typeWater ? '✔' : '' }}
              </span> -->
                <el-button circle type="success" style="border: none" plain v-if="row.typeWater">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="大气" prop="typeGas" width="60" align="center">
              <template #default="{ row }">
                <!-- <span>
                {{ row.typeGas ? '✔' : '' }}
              </span> -->

                <el-button circle type="success" style="border: none" plain v-if="row.typeGas">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="噪音" prop="typeNoise" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.typeNoise">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="废弃物" prop="typeWaste" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.typeWaste">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="土壤" prop="typeSoil" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.typeSoil">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
            <zm-table-column label="其他" prop="typeOther" width="60" align="center">
              <template #default="{ row }">
                <el-button circle type="success" style="border: none" plain v-if="row.typeOther">
                  <span class="text-[#259644]">
                    {{ '✔' }}
                  </span>
                </el-button>
                <span v-else></span>
              </template>
            </zm-table-column>
          </zm-table-column>

          <zm-table-column label="控制措施" prop="controlMethod" align="center" />
          <zm-table-column label="创建日期" prop="createTime" width="160" align="center">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </zm-table-column>
          <zm-table-column label="备注" prop="remark" align="center" />

          <zm-table-column label="操作" width="120" fixed="right" align="center" action>
            <template #default="{ row }">
              <el-button type="primary" link @click="editRow(row)">编辑</el-button>
              <el-button type="danger" link @click="deleteRow(row)">删除</el-button>
            </template>
          </zm-table-column>
        </zm-table>

        <!-- 分页 -->
        <div class="mt-2 flex justify-right">
          <el-pagination
            v-model:current-page="pagination.pageNo"
            v-model:page-size="pagination.pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background />
        </div>
      </ContentWrap>
    </el-col>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" destroy-on-close>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        v-loading="formLoading">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序" prop="process">
              <el-input v-model="formData.process" placeholder="请输入工序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="步骤分解" prop="stepBreak">
              <el-input v-model="formData.stepBreak" placeholder="请输入步骤分解" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境因素" prop="environmentElement">
              <el-input v-model="formData.environmentElement" placeholder="请输入环境因素" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="控制措施" prop="controlMethod">
              <el-input
                type="textarea"
                v-model="formData.controlMethod"
                placeholder="请输入控制措施"
              />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时态" prop="timeValue">
              <el-radio-group v-model="formData.timeValue">
                <el-radio label="timeBefore">过去</el-radio>
                <el-radio label="timeNow">现在</el-radio>
                <el-radio label="timeFuture">将来</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="statusValue">
              <el-radio-group v-model="formData.statusValue">
                <el-radio label="statusNormal">正常</el-radio>
                <el-radio label="statusException">异常</el-radio>
                <el-radio label="statusDanger">紧急</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="环境影响类型" prop="typeValue">
              <el-radio-group v-model="formData.typeValue">
                <el-radio label="typeEnergy">能源/资源耗用</el-radio>
                <el-radio label="typeWater">水体污染</el-radio>
                <el-radio label="typeGas">大气污染</el-radio>
                <el-radio label="typeNoise">噪声污染</el-radio>
                <el-radio label="typeWaste">废弃物</el-radio>
                <el-radio label="typeSoil">土壤污染</el-radio>
                <el-radio label="typeOther">其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="控制措施" prop="controlMethod">
              <el-input
                type="textarea"
                v-model="formData.controlMethod"
                placeholder="请输入控制措施" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在部门" prop="deptId">
              <el-tree-select
                clearable
                v-model="formData.deptId"
                :data="deptList2"
                :props="defaultProps"
                check-strictly
                node-key="id"
                filterable
                placeholder="请选择所在部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </el-row>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { IotEnvironmentApi } from '@/api/pms/qhse/index'
import { formatDate } from '@/utils/formatTime'
import { defaultProps } from '@/utils/tree'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import DeptTree from '@/views/system/user/HazardTree.vue'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents()

// 表格数据
const deptList2 = ref<Tree[]>([]) // 树形结构
const tableData = ref([])
const total = ref(0)
const isLeftContentCollapsed = ref(false)

// 筛选参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  process: '',
  stepBreak: '',
  environmentElement: '',
  deptId: null
})

const pagination = reactive({
  pageNo: 1,
  pageSize: 10
})

const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  pagination.pageNo = 1
  getList()
}

// 分页和查询
const queryFormRef = ref()
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNo = 1 // 重置为第一页

  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNo = val
  getList()
}

const downloadFile = (response) => {
  // 创建 blob 对象
  const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })

  // 获取文件名
  let fileName = '环境因素评价矩阵.xlsx'
  const disposition = response.headers ? response.headers['content-disposition'] : ''
  if (disposition) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
    const matches = filenameRegex.exec(disposition)
    if (matches != null && matches[1]) {
      fileName = matches[1].replace(/['"]/g, '')
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    exportLoading.value = true
    // 调用导出接口
    const response = await IotEnvironmentApi.exportEnvironment(queryParams)

    // 下载文件
    downloadFile(response)
    exportLoading.value = false
  } catch (error) {
    ElMessage.error('导出失败，请重试')
    console.error('导出错误:', error)
  } finally {
    exportLoading.value = false
  }
}

const getList = async () => {
  const res = await IotEnvironmentApi.getEnvironmentList(queryParams)
  tableData.value = res.list
  total.value = res.total
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

// 表单数据
const formData = ref({
  process: '',
  stepBreak: '',
  environmentElement: '',
  timeValue: '', // 单选时态值
  statusValue: '', // 单选状态值
  typeValue: '', // 单选影响类型值
  controlMethod: '',
  remark: '',
  deptId: null as number | null
})

// 表单验证规则
const formRules = {
  stepBreak: [{ required: true, message: '请输入步骤分解', trigger: 'blur' }],
  environmentElement: [{ required: true, message: '请输入环境因素', trigger: 'blur' }],
  controlMethod: [{ required: true, message: '请输入控制措施', trigger: 'blur' }],
  timeValue: [{ required: true, message: '请选择时态', trigger: 'change' }],
  statusValue: [{ required: true, message: '请选择状态', trigger: 'change' }],
  typeValue: [{ required: true, message: '请选择环境影响类型', trigger: 'change' }]
}

// 表单引用
const formRef = ref()

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '新增环境因素'
  resetFormData()
  dialogVisible.value = true
}

// 编辑行
const editRow = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑环境因素'

  // 构造表单数据
  formData.value = {
    ...row,
    timeValue: '', // 初始化单选值
    statusValue: '', // 初始化单选值
    typeValue: '' // 初始化单选值
  }

  // 设置单选值
  if (row.timeBefore) formData.value.timeValue = 'timeBefore'
  if (row.timeNow) formData.value.timeValue = 'timeNow'
  if (row.timeFuture) formData.value.timeValue = 'timeFuture'

  if (row.statusNormal) formData.value.statusValue = 'statusNormal'
  if (row.statusException) formData.value.statusValue = 'statusException'
  if (row.statusDanger) formData.value.statusValue = 'statusDanger'

  if (row.typeEnergy) formData.value.typeValue = 'typeEnergy'
  if (row.typeWater) formData.value.typeValue = 'typeWater'
  if (row.typeGas) formData.value.typeValue = 'typeGas'
  if (row.typeNoise) formData.value.typeValue = 'typeNoise'
  if (row.typeWaste) formData.value.typeValue = 'typeWaste'
  if (row.typeSoil) formData.value.typeValue = 'typeSoil'
  if (row.typeOther) formData.value.typeValue = 'typeOther'

  dialogVisible.value = true
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 这里应该调用实际的API删除
      await IotEnvironmentApi.deleteEnvironment(row.id)

      ElMessage.success('删除成功')
      getList() // 重新获取列表
    })
    .catch(() => {
      // 取消删除
    })
}

// 重置表单数据
const resetFormData = () => {
  formData.value = {
    process: '',
    stepBreak: '',
    environmentElement: '',
    timeValue: '',
    statusValue: '',
    typeValue: '',
    controlMethod: '',
    remark: '',
    deptId: null
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 取消表单
const cancelForm = () => {
  dialogVisible.value = false
  resetFormData()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 根据单选值更新布尔值
    const updatedData = {
      ...formData.value,
      timeBefore: formData.value.timeValue === 'timeBefore',
      timeNow: formData.value.timeValue === 'timeNow',
      timeFuture: formData.value.timeValue === 'timeFuture',
      statusNormal: formData.value.statusValue === 'statusNormal',
      statusException: formData.value.statusValue === 'statusException',
      statusDanger: formData.value.statusValue === 'statusDanger',
      typeEnergy: formData.value.typeValue === 'typeEnergy',
      typeWater: formData.value.typeValue === 'typeWater',
      typeGas: formData.value.typeValue === 'typeGas',
      typeNoise: formData.value.typeValue === 'typeNoise',
      typeWaste: formData.value.typeValue === 'typeWaste',
      typeSoil: formData.value.typeValue === 'typeSoil',
      typeOther: formData.value.typeValue === 'typeOther'
    }

    // 删除临时单选字段
    delete updatedData.timeValue
    delete updatedData.statusValue
    delete updatedData.typeValue

    if (isEdit.value) {
      // 更新操作
      await IotEnvironmentApi.updateEnvironment(updatedData)
      ElMessage.success('更新成功')
    } else {
      // 创建操作
      await IotEnvironmentApi.createEnvironment(updatedData)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  // 初始化数据
  getList()
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>

<style scoped lang="scss">
::v-deep .el-table__header th {
  border: 0.3px solid #adb0b7;
}

.factor-matrix .toolbar {
  margin: 12px 0;
  display: flex;
  gap: 8px;
  align-items: center;
}

.el-table .row-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 6px;
}

.el-checkbox .el-checkbox__input {
  margin-left: 6px;
}
</style>
