<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-input
          v-model="queryParams.status"
          placeholder="请输入状态"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="提交时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['workflow:process:ownExport']"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="filteredProjectData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"></el-table-column>

      <el-table-column label="项目申报名" align="center" :min-width="240">
        <template slot-scope="scope">
          <el-tag size="medium">{{ scope.row.projectName }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="projectLeader" label="项目负责人" align="center" width="180"></el-table-column>
      <el-table-column prop="projectAppStTime" label="申报开始日期" align="center" width="180"></el-table-column>
      <el-table-column prop="projectAppEndTime" label="申报结束日期" align="center" width="180"></el-table-column>
      <el-table-column prop="projectBudget" label="项目预算（万）" align="center" width="180"></el-table-column>
      <el-table-column prop="projectLeaderPhone" label="负责人电话" align="center" width="180"></el-table-column>
      <el-table-column prop="project_app_status" label="立项状态" align="center" width="180">
        <template slot-scope="scope">
          <el-tag size="medium" :type="info">
            <span :class="statusClass(scope.row.projectAppStaus)">
              {{ statusText(scope.row.projectAppStaus) }}
            </span>
        </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button 
            icon="el-icon-refresh-right"
            type="primary"
            @click="handleApplication(scope.row)" 
            size="mini"
            style="width: 80px"
          >修改重审</el-button>
          
          <el-button 
            type="success" 
            icon="el-icon-tickets"
            @click="handleDetail(scope.row)" 
            size="mini"
            style="width: 80px"
          >查看详情</el-button>
          
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="totalProjects > 0"
      :total="totalProjects"
      :page.sync="currentPage"
      :limit.sync="pageSize"
      @pagination="filterData"
    />

    <el-dialog title="项目详情" :visible.sync="detailDialogVisible">
      <el-form :model="currentProject" label-width="120px">
        <el-form-item label="项目名称">
          <el-input v-model="currentProject.projectName" disabled></el-input>
        </el-form-item>
        <el-form-item label="项目负责人">
          <el-input v-model="currentProject.projectLeader" disabled></el-input>
        </el-form-item>
        <el-form-item label="申报开始日期">
          <el-input v-model="currentProject.projectAppStTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="申报结束日期">
          <el-input v-model="currentProject.projectAppEndTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="项目预算（万）">
          <el-input v-model="currentProject.projectBudget" disabled></el-input>
        </el-form-item>
        <el-form-item label="负责人电话">
          <el-input v-model="currentProject.projectLeaderPhone" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { listDeclaredApplications } from "@/api/scientific/application";
import { listProcess } from "@/api/workflow/process";

export default {
  data() {
    return {
      queryParams: {
        projectName: '',
        status: '',
        startDate: '',
        endDate: '',
        pageNum: 1,
        pageSize: 10,
        processKey: undefined,
        processName: "项目立项审批",
        category: "004"
      },
      projectData: [],
      filteredProjectData: [],
      totalProjects: 0,
      currentPage: 1,
      pageSize: 10,
      detailDialogVisible: false,
      currentProject: {},
      loading: false,
      showSearch: true,
      dateRange: [],
      deploymentId: '',
      definitionId: '',
      ids: null
    };
  },
  methods: {
    handleQuery() {
      this.currentPage = 1;
      this.filterData();
    },
    resetQuery() {
      this.queryParams = {
        projectName: '',
        status: '',
        startDate: '',
        endDate: '',
        pageNum: 1,
        pageSize: 10,
      };
      this.dateRange = [];
      this.filterData();
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.filterData();
    },
    fetchProjectData() {
      this.loading = true;
      listDeclaredApplications()
        .then(response => {
          console.log('API response:', response);
          //  response.rows.filter(item => item.category === '002' && item.processStatus === 'completed');
          this.projectData = response.data.filter(item => item.projectAppStaus === '3')

          let parseData = response.data.filter(item => item.projectAppStaus === '3')
          console.log(parseData)
          this.filterData();
        })
        .catch(error => {
          console.error('Error fetching project data:', error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    filterData() {
      let filteredData = this.projectData;

      if (this.queryParams.projectName) {
        filteredData = filteredData.filter(project =>
          project.projectName.includes(this.queryParams.projectName.trim())
        );
      }

      if (this.queryParams.status) {
        filteredData = filteredData.filter(project =>
          project.projectAppStaus === this.queryParams.status.trim()
        );
      }

      if (this.dateRange.length) {
        const [start, end] = this.dateRange;
        filteredData = filteredData.filter(project => {
          const projectStartTime = new Date(project.projectAppStTime);
          return projectStartTime >= new Date(start) && projectStartTime <= new Date(end);
        });
      }

      this.totalProjects = filteredData.length;
      this.filteredProjectData = filteredData.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    handleApplication(row) {
      this.loading = true;
      this.reset();
      const upProjectId = row.projectId || this.ids;

      listProcess(this.queryParams).then(response => {
        this.processParams = response.rows[0];
        this.deploymentId = this.processParams.deploymentId;
        this.definitionId = this.processParams.definitionId;

        this.$router.push({
          path: `/workflow/process/proj_app/${this.deploymentId}?definitionId=${this.definitionId}`,
          query: {
            projectId: upProjectId
          }
        });
      }).catch(error => {
        console.error('Error fetching process data:', error);
      }).finally(() => {
        this.loading = false;
      });
    },
    handleDetail(row) {
      this.currentProject = row;
      this.detailDialogVisible = true;
    },
    reset() {
      // Any additional reset logic
    },
    statusClass(status) {
      switch (status) {
        case '0':
          return 'status-unapproved'; // 未立项
        case '2':
          return 'status-under-review'; // 审核中
        case '3':
          return 'status-approved'; // 已立项
        default:
          return '';
      }
    },
    statusText(status) {
      switch (status) {
        case '0':
          return '未立项';
        case '2':
          return '审核中';
        case '3':
          return '已立项';
        default:
          return '未知状态';
      }
    }
  },
  mounted() {
    this.fetchProjectData();
  }
};
</script>