<template>
  <div>
    <div class="vue-element-page-wrap">
      <el-row class="page-search" justify="space-between" align="bottom">
        <el-form
                ref="queryFormRef"
                :model="queryForm"
                :inline="true"
                label-width="80px"
                label-position="left">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="操作时间" prop="queryForm.params.DateValue">
                <el-date-picker
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        v-model="queryForm.params.DateValue"
                        type="datetimerange"
                        unlink-panels
                        range-separator="To"
                        v-model:start-placeholder="queryForm.params.FROMDATE"
                        v-model:end-placeholder="queryForm.params.TODATE"
                        :shortcuts="shortcuts2"
                        :size="size"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="page-search-btns">
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button type="primary" @click="handleAdd">新建</el-button>
        </div>
      </el-row>
      <div>
        <!-- 表格组件 -->
        <el-table :data="undistributed_list"  border
                  v-loading="undistributed_loading" highlight-current-row>
          <el-table-column prop = "ERRORNAME" label="名称" width="180"></el-table-column>
          <el-table-column prop = "ERRORDESCRIPTION" label="描述" width="300"></el-table-column>
          <el-table-column prop = "CREATETIME" label="时间" width="280"></el-table-column>
          <el-table-column prop = "USERID" label="记录人" width="180"></el-table-column>
          <el-table-column prop = "IMG_URL" label="图片路径" width="380"></el-table-column>
          <el-table-column label="图片">
            <template v-slot="scope">
              <el-image
                      style="width: 100px; height: 100px; object-fit: cover;"
                      :src="scope.row.IMG_URL"
                      :preview-src-list="[scope.row.IMG_URL]"
                      @click="handlePictureCardClick(scope.row.IMG_URL)"
              ></el-image>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <!-- 图片预览弹窗 -->
<!--        <el-dialog :visible.sync="dialogVisible" size="tiny">-->
<!--          <img width="100%" :src="previewImageUrl" alt="Preview Image" />-->
<!--        </el-dialog>-->
      <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryForm.pageNum"
                  v-model:pageSizeTo="queryForm.pageSize" @pagination="handleQuery" />
    </div>
    <div>
      <el-drawer v-model="boxDrawer" title="创建记录">
        <form @submit.prevent="submitForm">
          <div style="margin: 10px">
            <label for="name">异常类型:</label>
            <input type="text" v-model="record.name" id="name" value="WMS" required />
          </div>
          <div style="margin: 10px">
            <label for="description">描述:</label>
            <textarea v-model="record.description" id="description" rows="4"></textarea>
          </div>
          <div style="margin: 10px">
            <label for="file">上传图片:</label>
            <input type="file" @change="handleFileChange" id="file" accept="image/*" />
          </div>
          <button type="submit" style="align: center">提交</button>
          <div v-if="filePreviewUrl">
            <h3>图片预览：</h3>
            <img :src="filePreviewUrl" alt="预览图片" />
          </div>
        </form>

      </el-drawer>
    </div>
  </div>
</template>

<script>
  import {onMounted} from "vue";
  import {getQueryPageList} from "@/api/common";
  import {ElMessageBox} from "element-plus";
  import { localStorage } from "@/utils/storage";
  export default {
    data() {
      return {
        queryForm: {
          queryId: "getErrorLogList",
          version: "00001",
          params: {
            DateValue: '',
            FROMDATE: '',
            TODATE: '',
            IS_SURE: ''
          },
          pageNum: 1,
          pageSize: 10
        },
        boxDrawer: false,
        dialogVisible: false,
        previewImageUrl: '',
        record: {
          name: '',
          description: '',
        },
        selectedFile: null,
        filePreviewUrl: null,
        undistributed_loading: false,
        undistributed_list : [] ,
      };

      onMounted(() => {
        handleQuery()
        updateTableHeight();
      })
    },


    methods: {
      handlePictureCardClick(imageUrl) {
        console.log(imageUrl)
        this.previewImageUrl = imageUrl;
        this.dialogVisible = true;
        console.log(this.dialogVisible)
      },
      handleAdd() {
        this.boxDrawer = true;
      },

      async  handleQuery() {
        if (this.queryForm.params.DateValue.length > 0) {
          this.queryForm.params.FROMDATE = this.queryForm.params.DateValue[0]
          this.queryForm.params.TODATE = this.queryForm.params.DateValue[1]
        }
        await getQueryPageList(this.queryForm)
                .then((res) => {
                  if (res.data.list.length > 0) {
                    this.undistributed_list = res.data.list
                    this.total = res.data.total
                  } else {
                    this.undistributed_list = res.data.list
                    // proxy.$ElMessage.success('查询结果为空');
                  }

                })
      },
      handleFileChange(event) {
        const file = event.target.files[0];
        if (file && file.type.startsWith('image/')) {
          this.selectedFile = file;
          this.filePreviewUrl = URL.createObjectURL(file);
        } else {
          this.selectedFile = null;
          this.filePreviewUrl = null;
          alert('请选择一张图片文件');
        }
      },
      async submitForm() {
        if (!this.record.name || !this.record.description || !this.selectedFile) {
          alert('请填写完整的信息并选择一张图片');
          return;
        }

        const formData = new FormData();
        formData.append('user',localStorage.get('userId'));
        formData.append('name', this.record.name);
        formData.append('description', this.record.description);
        formData.append('file', this.selectedFile);

        try {
          const response = await fetch('http://172.22.10.217:22202/api/records', {
            method: 'POST',
            body: formData,
          });
          console.log(response)
          if (response.ok) {
            ElMessageBox.alert("新建成功", {
              confirmButtonText: 'OK'
            })
            // 这里可以清空表单或进行其他操作
            this.boxDrawer = false;
          } else {
            console.error('提交失败:', response.statusText);
          }
        } catch (error) {
          console.error('提交出错:', error);
        }
      },
    },
  };
</script>