<template>
  <div>
    <a-button @click="refreshData" type="primary" style="margin: 15px 30px 15px 15px;">刷 新</a-button>
    <a-dropdown-button @click="handleButtonClick">
      总公司园区
      <template #overlay>
        <a-menu @click="handleMenuClick">
          <a-menu-item key="1">
            <UserOutlined />
            总公司园区
          </a-menu-item>
        </a-menu>
      </template>
      <template #icon><down-outlined /></template>
    </a-dropdown-button>
	<span style="margin: 15px 60px 15px 15px;"> 共计 {{dataSize}} 条数据</span>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :row-selection="rowSelection" bordered>
      <template #bodyCell="{ column, text, record }">
        <template v-if="['advice'].includes(column.dataIndex)">
          <div class="adviceBox">
              <span style="font-size: 1rem">{{ text }}</span>
              <br /><br />
              <span >{{record.createTime}}</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'image'">
          <div class="image-container">
            <a-image
              v-if="record.urlList!=0"
              v-for="(filename, index) in record.urlList"
              :width="150"
              :height="150"
              :src="`${imageBaseUrl}${filename}`"/>

          </div>
        </template>
        <template v-else-if="column.dataIndex === 'reply'">
          <a-textarea :rows="4"/>
          <a-button type="primary" style="float: right">回 复</a-button>
        </template>
        <template v-else-if="column.dataIndex === 'edit'">
          <a-popconfirm
            title="你确定要删除这条信息吗?"
            ok-text="是"
            cancel-text="否"
            @confirm="deleteAdviceInfo(record.key)"
            @cancel="cancel">
              <a-button type="link">删 除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts">
import { cloneDeep } from 'lodash-es';
import { reactive, ref, defineComponent} from 'vue';
import type { UnwrapRef } from 'vue';
import axios from 'axios';
import {Image} from "ant-design-vue";
import type { MenuProps } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';
import {baseUrl, imageBaseUrl} from '@/config.js'

interface DataItem {
  key: string;
  advice: string;
  urlList: any;
  createTime: string;
}
const columns = [
  {
    title: '意见及建议',
    dataIndex: 'advice',
    width: '20%',
  },
  {
    title: '图片',
    dataIndex: 'image',
    width: '40%',
  },
  {
    title: '回复',
    dataIndex: 'reply',
    width: '20%',
  },
  {
    title: '操作',
    dataIndex: 'edit',
    width: '15%'
  }
];
const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});
let dataSource = ref()
let data: DataItem[] = [];
let dataSize = 0

const edit = (key: string) => {
  editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const save = (key: string) => {
  Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
  delete editableData[key];
};
const cancel = (key: string) => {
  delete editableData[key];
};

const handleButtonClick = (e: Event) => {
  console.log('click left button', e);
};
const handleMenuClick: MenuProps['onClick'] = e => {
  console.log('click', e);
};

const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
    console.log(selected, selectedRows, changeRows);
  },
});
export default defineComponent({
  components: {
    'a-image':Image,
    DownOutlined
  },
  data(){
    return{
      columns,
      editableData,
      edit,
      save,
      cancel,
      dataSource,
      imageBaseUrl,
      rowSelection,
      handleButtonClick,
      handleMenuClick,
	  dataSize
    }
  },
  methods:{
   async mygetData(){
      try {
        const response = await axios.get(baseUrl+'/queryReview');
		this.dataSize = response.data.length
        for (let item of response.data){
          const urlList = item.imageInfoList.trim().split(/\s*,\s*/)
          data.push({
            key: item.id,
            advice: item.advice,
            urlList: urlList,
            createTime: item.createTime
          })
        }
        dataSource.value = data;
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
   refreshData(){
     data = []
     this.mygetData()
   },

   async deleteAdviceInfo(key:string){
      await axios.get(baseUrl+'/deleteAdviceInfo',{params: {"id":key}})
        .then(response =>{
          // 删除成功后，刷新页面
          dataSource.value = dataSource.value.filter(item => item.key !== key);
        }).catch(error => {
          console.error('删除失败:', error);
        });
   }
  },

  mounted() {
	const now = Date.now();
	const expirationTime = parseInt(localStorage.getItem('hasPassedPasswordCheck_expiration'));
	const pass = localStorage.getItem('hasPassedPasswordCheck')
	if(pass && !(expirationTime && now > expirationTime)){
		this.mygetData()
	}else{ 
		// 数据已过期，从localStorage中移除
	    localStorage.removeItem('hasPassedPasswordCheck');
	    localStorage.removeItem('hasPassedPasswordCheck_expiration');
		uni.reLaunch({
		  url: './checkPassword'
		});
	}
  }
});

</script>
<style scoped>
.adviceBox {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%; /* 宽度与单元格相同 */
  height: 100%; /* 高度与单元格相同 */
  max-height: 20vh;
  overflow-y: auto; /* 当内容超出时显示垂直滚动条 */
  padding: 0.5rem; /* 内边距，可根据需要调整 */
  box-sizing: border-box; /* 确保padding和border包含在width和height内 */
}

.adviceBox span:first-child {
  text-indent: 2em; /* 首行缩进两格 */
  white-space: pre-line; /* 保留换行符和空格 */
  font-size: 1rem; /* 文字大小 */
  flex-grow: 1; /* 占据剩余空间，确保createTime位于底部 */
}

.adviceBox span:last-child {
  align-self: flex-end; /* 将createTime定位至右下角 */
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.editable-row-operations a {
  margin-right: 8px;
}

.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px; /* 图片之间的间距 */
}

</style>
