<script setup>
import {onBeforeMount, onMounted, onBeforeUnmount, reactive, ref, unref, computed} from 'vue';
import {useStore, mapGetters, mapState} from "vuex";
import {project_list, prd_list, prd_add, prd_get, prd_update, prd_delete, prd_history} from "@/apis/product.js";
import {storage} from "@/storage/storage.js";
import {onBeforeRouteLeave} from "vue-router";


// 注册vuex
const store = useStore()


// region 表单代码


// 点击搜索时提交的数据
const fromData = reactive({
  project: '全部',
})
// region 表格数据代码
// 表格展示的数据
const tableData = ref([])

// 过滤条件数据
const projectList = ref([])

const currentPage = ref(1)
const pageSize = ref(20)

const total = ref(0)

const history_dialog_id = ref(1)

let local_storage_array = storage.get("prd_history")

// 处理翻页
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  get_table_data(currentPage.value, pageSize.value, fromData.project)
}

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize
  get_table_data(currentPage.value, pageSize.value, fromData.project)
}

// 处理历史记录对话框
const changeDialogStatus = (id) => {
  history_dialog_id.value = id
  console.log('changeDialogStatus', id)
  get_history(history_dialog_id.value)
}


// 定义数据源
const history_data = ref([])

// 定义对话框开关
let history_dialog_show = ref(false)

// 通过接口获取历史数据
function get_history(id) {
  prd_history(id).then(res => {
    console.log('get_history')
    if (Array.isArray(res)) {
      history_data.value = [...res]
    }
    history_dialog_show.value = true
  }).catch(err => {
    console.log(err)
  });
}

const handleClose = () => {
  history_dialog_show.value = false
  history_data.value = []
}


// 数据提交 点击搜索按键提交数据
const submitSearch = async () => {
  tableData.value = []
  await get_table_data(currentPage.value, pageSize.value, fromData.project).then(
      res => {
        if (Array.isArray(res)) {
          tableData.value = [...res]

        } else {

        }
      }
  ).catch(
      err => {
      }
  )
}

// 更新localstorage
function update_local_storage(id, update_at, update_mode = true) {
  if (local_storage_array !== null) {
    let find_local_data = false
    local_storage_array.forEach((item) => {
      if (item["id"] === id) {
        if (update_mode === true) {
          item["update_at"] = update_at
        }
        find_local_data = true
        return true
      }
    })
    if (!find_local_data) {
      local_storage_array.push({id, update_at})
      return true
    }
    return false
  } else {
    local_storage_array = new Array({id, update_at})
  }
}

const update_table_data = (id) => {
  tableData.value.forEach((item) => {
    if (item.id === id) {
      item.have_update = false
    }
  })
}

const mark_read = (id, update_at) => {
  update_local_storage(id, update_at)
  update_table_data(id)
  save_local_storage()
}

const save_local_storage = () => {
  tableData.value.forEach((table_item) => {
        update_local_storage(table_item["id"], table_item["update_at"], false)
      }
  )
  storage.remove('prd_history')
  storage.set('prd_history', local_storage_array)
}

// 通过异步请求获取影院列表数据
async function get_project_data() {
  projectList.value = []
  await project_list().then(res => {
    if (Array.isArray(res)) {
      projectList.value = [...res]
      projectList.value.unshift({'id': 0, 'project_name': '全部', is_delete: false})
    } else {
    }
  }).catch(err => {
        console.log(err)
      }
  )
}

// 通过异步请求获取影院列表数据
async function get_table_data(page_num = currentPage.value, page_size = pageSize.value, project_val = fromData.project) {
  // 获取数据
  tableData.value = []
  console.log('get_table_data')
  console.log(project_val)
  project_val = project_val === '全部' ? '' : project_val
  console.log(project_val)
  await prd_list(page_num, page_size, project_val).then(res => {
    total.value = res['count']
    if (Array.isArray(res['results'])) {
      tableData.value = [...res['results']]
      console.log(tableData.value)
    } else {
      console.log('get_table_data.res is not an array')
    }
  }).catch(err => {
        console.log(err)
      }
  )
  if (local_storage_array !== null) {
    //处理新收到标记
    tableData.value.forEach((table_item, table_index) => {
      let find_local_data = false
      table_item['have_update'] = false
      local_storage_array.forEach((local_item, local_index) => {
        if (table_item['id'] === local_item['id']) {
          find_local_data = true
          const table_datetime = new Date(table_item['update_at'])
          const local_datetime = new Date(local_item['update_at'])
          if (table_datetime > local_datetime) {
            table_item['have_update'] = true
          }
        }
      })
      if (!find_local_data) {
        table_item['have_update'] = true
      }
    })
  }
}

// 定义生命周期，在加载时获取一次表格数据
onMounted(
    async () => {
      await get_project_data();
      await get_table_data(currentPage.value, pageSize.value, fromData.project);
    }
)

onBeforeUnmount(
    () => {
      save_local_storage()
    }
)
onBeforeRouteLeave(
    () => {
      save_local_storage()
    }
)


// endregion

</script>

<template>
  <el-form
      :model="fromData"
      :inline="true"
      class="search_form"
  >
    <el-form-item label="所属项目" label-width="90">
      <el-select v-model="fromData.project" placeholder="请选择">
        <el-option v-for="item in projectList" :key="item['project_name']" :label="item['project_name']"
                   :value="item['project_name']"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitSearch">搜索</el-button>
    </el-form-item>
    <!--    <el-button style="margin-right: 0">添加</el-button>-->
  </el-form>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="project" label="所属项目" min-width="200"></el-table-column>
    <el-table-column prop="prd_version" label="版本" min-width="200"></el-table-column>
    <el-table-column prop="prd_doc_link" label="产品原型链接" min-width="300" show-overflow-tooltip>
      <template v-slot="scope">
        <a target="_blank" style="color:#007bff;" v-if="scope.row.prd_doc_link!=null"
           @click="mark_read(scope.row.id, scope.row.update_at)"
           v-bind:href="scope.row.prd_doc_link">
          {{
            scope.row.prd_doc_link.length > 30 ? scope.row.prd_doc_link.slice(0, 30) + '...' : scope.row.prd_doc_link
          }}
        </a>
        <!--        <span v-else> {{ scope.row.prd_doc_link }}</span>-->
      </template>
    </el-table-column>
    <el-table-column prop="prd_comment" label="版本描述" min-width="260">
      <template #default="{ row }">
        <el-tooltip
            class="item"
            popper-class="custom-tooltip"
            effect="dark"
            :raw-content="true"
            :content="row.prd_comment.split('\n').join('<br>')"
            placement="top-end">
          <span>{{ row.prd_comment.length > 10 ? row.prd_comment.slice(0, 10) + '...' : row.prd_comment }}</span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="update_at" label="最后更新时间" min-width="210">
      <template v-slot="scope">
        <span>{{ scope.row.update_at }}</span><sup v-if="scope.row.have_update"
                                                   style="color: red; margin-left: 3px">有更新</sup>
      </template>
    </el-table-column>
    <el-table-column prop="id" label="历史文档" min-width="120">
      <template v-slot="scope">
        <el-button type="primary" size="small" @click="changeDialogStatus(scope.row.id)"
                   :disabled="!scope.row.have_history">查看
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        size="small"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>
  <template>
    <el-dialog v-model="history_dialog_show" title="历史记录" width="500px" :modal="true"
               :close-on-click-modal="false" :append-to-body="true" @close="handleClose">
      <el-table :data="history_data" style="width: 100%">
        <el-table-column prop="update_at" label="版本发布日期" min-width="100"></el-table-column>
        <el-table-column prop="history_doc_link" label="产品原型链接" min-width="300" show-overflow-tooltip>
          <template v-slot="scope">
            <a target="_blank" style="color:#007bff;" v-if="scope.row.history_doc_link!=null"
               v-bind:href="scope.row.history_doc_link">
              {{
                scope.row.history_doc_link.length > 30 ? scope.row.history_doc_link.slice(0, 30) + '...' : scope.row.history_doc_link
              }}
            </a>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </template>

</template>


<style>
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.search_form {
  display: flex;
  justify-content: flex-start;
}

.custom-tooltip {
  max-width: 500px; /* 设置最大宽度为 300px */
}
</style>
