<template>
  <div class="contentBox">
    <el-card class="card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item :label="proxy.$t('equipment.deviceModel')" prop="deviceModel">
          <el-input v-model="queryParams.deviceModel" :placeholder="proxy.$t('equipment.inputDeviceModel')" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search"  @click="handleQuery">{{proxy.$t('button.search')}}</el-button>
          <el-button icon="Refresh"   @click="resetQuery">{{proxy.$t('button.reset')}}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
          >{{proxy.$t('button.add')}}</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="maintenanceList" border>
        <el-table-column :label="proxy.$t('common.sort')" type="index" width="60" align="center" />
        <el-table-column :label="proxy.$t('equipment.deviceModel')" align="center" prop="deviceModel" />
        <el-table-column :label="proxy.$t('equipment.deviceImage')" align="center" prop="devicePic">
          <template #default="scope">
            <image-preview :height="50" :src="scope.row.devicePic" :width="50" />
          </template>
        </el-table-column>
        <el-table-column :label="proxy.$t('customer.createBy')" align="center" prop="createBy" />
        <el-table-column :label="proxy.$t('customer.createTime')" align="center" prop="createTime" width="160" />
        <el-table-column :label="proxy.$t('common.action')" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
            >{{proxy.$t('button.edit')}}</el-button>
            <el-button
                link
                type="primary"
                icon="delete"
                @click="handleDelete(scope.row)"
            >{{proxy.$t('button.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-if="total > 0"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @pagination="getList"
        />
      </div>
    </el-card>
    <el-dialog
        :title="title"
        v-model="visible"
        width="500px"
        append-to-body
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-width="appStore.language === 'zh_CN' ? '80px' : '120px'"
          label-position="right"
      >
        <el-form-item :label="proxy.$t('equipment.deviceModel')" prop="deviceModel">
          <el-input v-model="form.deviceModel" :placeholder="proxy.$t('common.select')" style="width: 300px" />
        </el-form-item>
        <el-form-item :label="proxy.$t('equipment.deviceImage')" prop="devicePic">
          <el-upload
              class="upload-demo"
              :action="upload.url"
              :headers="upload.headers"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :limit="1"
              accept=".jpg,.png"
              :show-file-list="false"
          >
            <template #default>
              <div v-if="!form.devicePic" class="upload-box">
                <el-icon><Plus /></el-icon>
                <div>{{proxy.$t('equipment.uploadImage')}}</div>
              </div>
              <div v-else class="upload-file">
                <el-image
                    :src="form.devicePic"
                    class="upload-image"
                    fit="cover"
                    :preview-src-list="[form.devicePic]"
                    :initial-index="0"
                    preview-teleported
                />
                <span class="delete-icon" @click.stop="handleRemove">
          <el-icon><Close /></el-icon>
        </span>
              </div>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                {{proxy.$t('equipment.limitImage')}}
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{proxy.$t('button.save')}}</el-button>
          <el-button @click="cancel">{{proxy.$t('button.cancel')}}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {getDeviceModelListApi, deleteDeviceModelApi, getDeviceModelDetailApi, editDeviceModelApi, addDeviceModelApi} from '@/api/equipment'
import {ElMessage, ElMessageBox} from "element-plus";
import { Plus, Close } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n';
import { globalHeaders } from '@/utils/request';
import {deleteDepartmentApi} from "@/api/customer/index.js";
import { useAppStore } from '@/store/modules/app';
const appStore = useAppStore();
const { proxy } = getCurrentInstance();
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const maintenanceList = ref([])
const { t } = useI18n();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  deviceModel:''
})
// 添加弹框相关的数据
const visible = ref(false)
const title = ref('')
const formRef = ref()

const form = reactive({
  deviceModel: '',
  devicePic: '',
})
const upload = reactive({
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
});
const rules = {
  deviceModel: [
    { required: true, message: proxy.$t('equipment.deviceModel'), trigger: 'blur' }
  ],
  devicePic: [
    { required: true, message:  proxy.$t('equipment.inputDeviceImage'), trigger: 'change' }
  ]
}

// 获取列表数据
const getList = async() => {
  loading.value = true
  // 这里应该调用后端API获取数据
  const res = await getDeviceModelListApi(queryParams);
  if(res.code === 200) {
    maintenanceList.value = res.rows || []
    total.value = res.total
  } else {
    ElMessage.error(res.msg)
  }
  loading.value = false
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryParams.deviceModel = ''
  handleQuery()
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
      proxy.$t('common.deleteItem'),
      proxy.$t('common.warning'),
      {
        confirmButtonText: proxy.$t('button.save'),
        cancelButtonText: proxy.$t('button.cancel'),
        type: "warning"
      }

  ).then(async () => {
    const res = await deleteDeviceModelApi(row.id)
    if (res.code === 200) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
    getList()
  }).catch(() => {})
}
// 打开新增弹框
const handleAdd = () => {
  visible.value = true
  title.value = proxy.$t('button.add')
  form.devicePic = ''
  form.deviceModel = ''
  formRef.value?.resetFields()
}
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt50K = file.size / 1024 < 50
  console.log(file,'0000')
  if (!isJPG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt50K) {
    ElMessage.error('图片大小不能超过 50KB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response, file) => {
  form.devicePic = response.data.url
  ElMessage.success('上传成功')
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const handleRemove = (file) => {
  form.devicePic = ''
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    // 这里添加提交逻辑
    const res  = title.value === proxy.$t('button.add') ? await addDeviceModelApi(form): await editDeviceModelApi(form)
    if(res.code === 200) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
    getList()
    cancel()
  } catch (error) {
    console.error(proxy.$t('common.formValidateError'), error)
  }
}

const cancel = () => {
  visible.value = false
  form.devicePic = ''
  form.deviceModel = ''
}
// 编辑
const handleUpdate = async(row) => {
  console.log(row,'---')
  const res = await getDeviceModelDetailApi(row.id)
  if(res.code === 200) {
    form.deviceModel = res.data.deviceModel
    form.devicePic = res.data.devicePic
    form.id = res.data.id
    title.value = proxy.$t('button.edit')
    visible.value = true
  } else {
    ElMessage.error(res.msg)
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.contentBox {
  height:calc(100vh - 130px);
  margin:20px;
  .card {
    width:100%;
    height: 100%;
    overflow-y: scroll;
  }
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.upload-box, .upload-file {
  width:200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  cursor: pointer;
  z-index: 1;
}

.delete-icon:hover {
  background-color: rgba(0, 0, 0, 0.7);
}
:deep(.el-form-item__label) {
  justify-content: flex-end;
}
</style>