<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="add()"
        >新增项目</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :table-layout="'fixed'"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          prop="project.ID"
          label="编号"
          :width="200"
        />
        <el-table-column
          prop="project.projectName"
          label="名称"
        >
          <template #default="scope">
            <el-link
              link
              type="primary"
              size="large"
              @click="view"
            >
              {{ scope.row.project.projectName }}
            </el-link>
          </template>

        </el-table-column>
        <el-table-column
          prop="project.startTime"
          label="开始日期"
          :formatter="(row, column, cellValue) => cellValue?.split('T')[0] || ''"
        />
        <el-table-column
          prop="project.remark"
          label="备注"
        />
        <el-table-column
          align="left"
          fixed="right"
          label="操作"
          :width="300"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="edit"
              @click="editProject(scope.row.project)"
            >编辑</el-button>
            <el-button
              type="primary"
              link
              icon="delete"
              @click="deleteProject(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>

      <el-dialog
        v-model="addProjectDialog"
        title="路口项目"
        width="600"
      >
        <el-form
          ref="projectForm"
          :rules="rules"
          :model="projectInfo"
          label-width="100px"
          style="padding: 15px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="项目名称："
                :inline="false"
                prop="projectName"
              >
                <el-input v-model="projectInfo.projectName" />
              </el-form-item>
              <el-form-item
                label="开始时间："
                :inline="false"
                prop="startTime"
              >
                <el-date-picker
                  v-model="projectInfo.startTime"
                  type="date"
                  placeholder="Pick a day"
                  size="default"
                />
              </el-form-item>
              <el-form-item
                label="备注："
                :inline="false"
              >
                <el-input
                  v-model="projectInfo.remark"
                  type="textarea"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeAddProjectDialog">取消</el-button>
            <el-button
              type="primary"
              @click="enterAddProjectDialog"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!--      抽屉-->
      <el-drawer
        v-model="viewProjectDialog"
        :show-close="false"
      >
        <template #header="{ close, titleId, titleClass }">
          <h4
            :id="titleId"
            :class="titleClass"
          >关联设备：</h4>

        </template>
        This is drawer content.
      </el-drawer>
    </div>
  </div>
</template>
<script setup>
import { delProject, getProjectList, updateProject, addProject } from '@/api/project'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const projectInfo = ref({})
const projectForm = ref(null)
const dialogFlag = ref('add')
const isFlag = ref('')
const addProjectDialog = ref(false)
const viewProjectDialog = ref(false)

const rules = ref({
  projectName: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    // { min: 5, message: '最低5位字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择时间', trigger: 'blur' },
    // { min: 5, message: '最低5位字符', trigger: 'blur' }
  ]
})

// eslint-disable-next-line no-unused-vars
const getNowDay = () => {
  const timestamp = Date.now() // 获取当前时间戳，单位是毫秒
  projectInfo.value.startTime = new Date(timestamp)
}

const tableRowClassName = ({ row, rowIndex }) => {
  if ((rowIndex + 1) % 2 === 0) {
    return 'success-row'
  }
  return ''
}
const getTableData = async() => {
  const table = await getProjectList({ page: page.value, pageSize: pageSize.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

onMounted(() => {
  getTableData()
})

const view = (row) => {
  viewProjectDialog.value = true
  // projectInfo.value = JSON.parse(JSON.stringify(row))
  // projectInfo.value.installTime = new Date(projectInfo.value.installTime).toLocaleDateString()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const add = () => {
  projectInfo.value = {}
  dialogFlag.value = 'add'
  getNowDay()
  addProjectDialog.value = true
}

const closeAddProjectDialog = () => {
  projectForm.value.resetFields()
  addProjectDialog.value = false
  isFlag.value = ''
}

const enterAddProjectDialog = async() => {
  projectForm.value.validate(async valid => {
    if (valid) {
      const req = {
        ...projectInfo.value
      }
      if (dialogFlag.value === 'add') {
        const res = await addProject(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '创建成功' })
          await getTableData()
          closeAddProjectDialog()
        }
      }
      if (dialogFlag.value === 'edit') {
        const res = await updateProject(req)
        if (res.code === 0) {
          ElMessage({ type: 'success', message: '编辑成功' })
          await getTableData()
          closeAddProjectDialog()
        }
      }
    }
  })
}

const editProject = (row) => {
  dialogFlag.value = 'edit'
  projectInfo.value = JSON.parse(JSON.stringify(row))
  addProjectDialog.value = true
}
const deleteProject = (obj) => {
  ElMessageBox.confirm('您确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async() => {
      for (const prop in obj.relationDev) {
        if (Array.isArray(obj.relationDev[prop])) {
          if (obj.relationDev[prop].length !== 0) {
            ElMessage({
              type: 'warning',
              message: '删除失败，请先解绑该项目下的设备！',
            })
            return
          }
        }
      }
      const res = await delProject({ ID: obj.project.ID })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

</script>
<style>
.el-table .success-row {
  background: #f3fdef;
}

.onlinebox{
  width: 12px; height: 12px;border-radius: 50%; display: inline-block; margin-right: 4px; position: relative; top: 1px;
}

.el-dialog__header{
  border-bottom: 1px solid #e8eaec;
}
.el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
</style>
