<template>
  <div ref="tableContainer">
    <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 class="vue-element-page-table">
      <el-table
        :height="500"
        border
        v-loading="undistributed_loading"
        :data="undistributed_list"
        highlight-current-row
        row-key="id"
      > 
        <template v-for="(col, index) in undistributed_column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="col.field === 'IS_SURE'">
                <span v-if="scope.row[col.field] == 'Y'">是</span>
                <span v-else >否</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
        <template v-slot:empty>
          <svg-icon icon-class="noData" width="160px" height="160px" />
        </template>
      </el-table>
    </div>
    <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="创建记录">
      <el-form ref="formDataRef"  label-position="top" :model="queryParam">
          <el-form-item label="名称">
            <input type="text" v-model="state.record.name" id="name" required />
          </el-form-item>
          <el-form-item label="描述">
            <textarea v-model="state.record.description" id="description" rows="4"></textarea>
          </el-form-item>
          <el-form-item label="上传图片">
            <input type="file" @change="handleFileChange" id="file" accept="image/*" />
          </el-form-item>
        <el-button type="primary" @click="addRecords">新建</el-button>
        </el-form>
      <div v-if="state.filePreviewUrl">
        <h3>图片预览：</h3>
        <img :src="state.filePreviewUrl" alt="预览图片" />
      </div>
    </el-drawer>
  </div>
  </div>
  
</template>

<script lang="ts">
import { ref } from 'vue'
export default {
  name: "ExceptionRecord"
}
</script>

<script lang="ts" setup>
import { ElForm, ElMessageBox } from 'element-plus'
import { onMounted, reactive, toRefs, getCurrentInstance } from 'vue'
import { getQueryList,getQueryPageList } from '@/api/common'
import { bTableHeight } from "@/composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(0);
const { proxy }: any = getCurrentInstance();

const formDataRef = ref(ElForm)
const state = reactive({
  boxDrawer: false,
  loadings: false,
  button_print: false,
  queryForm: {
    queryId: "getCacheWareList",
    version: "00001",
    params: {
      DateValue: '',
      FROMDATE: '',
      TODATE: '',
      IS_SURE: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParam: {
      SITENAME:'SDK',
      USERID: '',
  },
  undistributed_loading: false,
  total: 0,
  record: {
    name: '',
    description: '',
  },
  selectedFile: null,
  filePreviewUrl: null,
  dynamicDrawerWidth : '',
})

const {
  queryForm,
  queryParam,
  undistributed_column,
  undistributed_loading,
  undistributed_list,
  boxDrawer,
  total,
  selectedFile,
  filePreviewUrl,
  TEMPList
} = toRefs(state)

const size = ref<'default' | 'large' | 'small'>('default');
const shortcuts2 = [
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
onMounted(() => {
  state.undistributed_column = [
    {
      header: '名称',
      field: 'MATERIALSPECNAME',
      hide: false
    },
    {
      header: '描述',
      field: 'SDK_ID',
      width: '100px',
      hide: false
    },
    {
      header: '时间',
      field: 'PHASE',
      // width: '100px',
      hide: false
    },
    {
      header: '记录人',
      field: 'MATERIALQUANTITY',
      width: '100px',
      hide: false
    },
    {
      header: '图片',
      field: 'UNIT',
      hide: false
    }
  ]
  handleQuery()
  updateTableHeight();
  // window.addEventListener('resize', handleResize);
})
function handleAdd() {
  state.boxDrawer = true;
}

function changeDrawerWidth() {
  state.dynamicDrawerWidth = '400px'; // 修改宽度为400px
}
async function handleQuery() {
  if (state.queryForm.params.DateValue.length > 0) {
    state.queryForm.params.FROMDATE = state.queryForm.params.DateValue[0]
    state.queryForm.params.TODATE = state.queryForm.params.DateValue[1]
  }
  await getQueryPageList(state.queryForm)
    .then((res: any) => {
      if (res.data.list.length > 0) {
        state.undistributed_list = res.data.list
        state.total = res.data.total
      } else {
        state.undistributed_list = res.data.list
        proxy.$ElMessage.success('查询结果为空');
      }

    })
}

function handleFileChange(event) {
  const file = event.target.files[0];
  console.log(file)
  if (file && file.type.startsWith('image/')) {
    state.selectedFile = file;
    state.filePreviewUrl = URL.createObjectURL(file);
    console.log(state.filePreviewUrl)
  } else {
    state.selectedFile = null;
    state.filePreviewUrl = null;
    ElMessageBox.alert('请选择一张图片文件', {
      confirmButtonText: 'OK'
    })
  }
}
await function addRecords() {
  console.log("*********************")
  if (!state.record.name || !state.record.description || !state.selectedFile) {
    ElMessageBox.alert('请填写完整的信息并选择一张图片', {
      confirmButtonText: 'OK'
    })
    return;
  }

  const formData = new FormData();
  formData.append('name', state.record.name);
  formData.append('description', state.record.description);
  formData.append('file', state.selectedFile);

  try {
    const response =  fetch('http://localhost:17878/api/records', {
      method: 'POST',
      body: formData,
    });

    if (response.ok) {
      const result =  response.json();
      console.log('提交成功:', result);
      // 这里可以清空表单或进行其他操作
    } else {
      console.error('提交失败:', response.statusText);
    }
  } catch (error) {
    console.error('提交出错:', error);
  }
}

</script>

<style scoped>
</style>
