<template>
  <!-- 集体审议内容（只读默认） -->
  <div class="meeting-section">
    <!-- 系统记录 -->
    <div class="system-records">
      <!-- <el-button
        v-if="!isView"
        style="margin-bottom: 20px"
        plain
        type="success"
        icon="el-icon-circle-plus"
        @click="addMeetingRecord"
      >
        添加记录
      </el-button> -->
      <CostAuditTable
        :table-data="meetingRecords"
        :columns="tableColumns"
        :show-index="true"
        :border="true"
        style="width: 100%"
        :show-pagination="true"
        :pagination="pagination"
        @pagination-change="onPaginationChange"
      >
        <!-- 附件列自定义内容 -->
        <template #attachments="{ row }">
          <el-button
            type="text"
            size="small"
            @click="viewMeetingAttachment(row)"
          >
            查看
          </el-button>
        </template>
        <!-- 操作列自定义内容 -->
        <template #action="{ row }">
          <el-button
            type="text"
            size="small"
            @click="handleViewMeetingRecord(row)"
          >
            查看
          </el-button>
          <!-- <el-button v-if="!isView" :disabled="isView" type="text" size="small" @click="editMeetingRecord(row)">
            修改
          </el-button>
          <el-button v-if="!isView" type="text" size="small" class="delete-btn" @click="deleteMeetingRecord(row.id)">
            删除
          </el-button> -->
        </template>
      </CostAuditTable>
    </div>
    <!-- 集体审议记录表单 -->
    <el-dialog
      title="集体审议记录"
      :visible.sync="meetingDialogVisible"
      width="60%"
      class="meeting-form-section"
      :modal="false"
      append-to-body
    >
      <el-form
        ref="meetingForm"
        :model="meetingForm"
        label-width="120px"
        class="meeting-form"
        :disabled="isView"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="审议形式">
              <el-input
                v-model="meetingForm.deliberationForm"
                placeholder="请填写"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审议时间开始">
              <el-date-picker
                v-model="meetingForm.beginTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审议时间结束">
              <el-date-picker
                v-model="meetingForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地点">
              <el-input
                v-model="meetingForm.location"
                placeholder="请填写"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主持人">
              <el-select
                v-model="meetingForm.hostPerson"
                placeholder="请选择人员"
                style="width: 100%"
              >
                <el-option
                  v-for="person in personList"
                  :key="person.id"
                  :label="person.name"
                  :value="person.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录人">
              <el-select
                v-model="meetingForm.recordPerson"
                placeholder="请选择人员"
                style="width: 100%"
              >
                <el-option
                  v-for="person in personList"
                  :key="person.id"
                  :label="person.name"
                  :value="person.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="参加人员">
              <el-input
                v-model="meetingForm.participants"
                placeholder="请填写"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="审议项目">
              <el-input
                v-model="meetingForm.projectName"
                placeholder="自动获取项目名称"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="监审单位id">
              <el-input
                v-model="meetingForm.enterpriseId"
                placeholder="自动获取监审单位id"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="审议情况">
              <el-input
                v-model="meetingForm.deliberationContent"
                type="textarea"
                :rows="4"
                placeholder="填写"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="审议结论意见">
              <el-input
                v-model="meetingForm.conclusionOpinion"
                type="textarea"
                :rows="4"
                placeholder="填写"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="审议记录附件">
              <UploadComponent
                :upload-mode="'multiple'"
                :files-list="meetingAttachmentList"
                button-text="选择文件"
                :is-disabled="isView"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="meetingDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import UploadComponent from '@/components/costAudit/UploadComponent.vue'
  import { getDeliberatePageList } from '@/api/taskProgressManage'
  import { getCollectiveDeliberateList } from '@/api/audit/collective.js'
  export default {
    name: 'DiscussionTab',
    components: { CostAuditTable, UploadComponent },
    props: {
      project: { type: Object, default: () => ({}) },
      // 默认只读
      isView: { type: Boolean, default: true },
    },
    data() {
      return {
        meetingDialogVisible: false,
        // 集体审议相关数据
        meetingRecords: [],

        // 集体审议表单数据
        meetingForm: {
          deliberationForm: '',
          beginTime: '',
          endTime: '',
          location: '',
          hostPerson: '',
          recordPerson: '',
          participants: '',
          projectName: '',
          enterpriseId: '',
          deliberationContent: '',
          conclusionOpinion: '',
          attachmentName: '',
          attachmentIds: '',
        },
        // 附件列表
        meetingAttachmentList: [],
        // 分页相关
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 记录最近一次查询方式与参数（确保翻页时按相同条件重查）
        lastQuery: {
          mode: 'project', // 'project' | 'task'
          id: '',
        },
        // 表格列配置
        tableColumns: [
          {
            prop: 'deliberationForm',
            label: '审议形式',
            align: 'left',
            width: 100,
          },
          { prop: 'location', label: '地点', align: 'left' },
          { prop: 'hostPerson', label: '主持人', align: 'center', width: 120 },
          { prop: 'beginTime', label: '审议时间', align: 'center', width: 150 },
          {
            prop: 'attachments',
            label: '附件',
            align: 'center',
            width: 60,
            slotName: 'attachments',
          },
          {
            prop: 'action',
            label: '操作',
            align: 'center',
            width: 150,
            slotName: 'action',
            showOverflowTooltip: false,
          },
        ],
        // 人员选择列表（占位）
        personList: [
          { id: '1', name: '张**' },
          { id: '2', name: '李**' },
          { id: '3', name: '王**' },
        ],
      }
    },
    mounted() {
      this.getMeetingRecords()
    },
    methods: {
      addMeetingRecord() {
        this.meetingForm = {
          deliberationForm: '',
          beginTime: '',
          endTime: '',
          location: '',
          hostPerson: '',
          recordPerson: '',
          participants: '',
          projectName: '',
          enterpriseId: '',
          deliberationContent: '',
          conclusionOpinion: '',
          attachmentName: '',
          attachmentIds: '',
        }
        // 清空附件列表
        this.meetingAttachmentList = []
        this.meetingDialogVisible = true
      },
      getMeetingRecords() {
        const pid =
          (this.project && (this.project.projectId || this.project.id)) || ''
        if (!pid) return
        // 记录最近一次查询
        this.lastQuery = { mode: 'project', id: pid }
        getDeliberatePageList({
          projectId: pid,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
        }).then((res) => {
          if (res.value && res.value.value) {
            this.meetingRecords = res.value.value.records || []
            this.pagination.total = res.value.value.total || 0
          }
        })
      },
      // 新增：按 taskId 加载集体审议记录（供父组件切换到“集体审议”时调用）
      loadRecordsByTask(taskId) {
        if (!taskId) return
        // 记录最近一次查询
        this.lastQuery = { mode: 'task', id: taskId }
        getCollectiveDeliberateList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          taskId: taskId,
        }).then((res) => {
          const payload = res && res.value
          this.meetingRecords = (payload && payload.records) || []
          this.pagination.total = (payload && payload.total) || 0
        })
      },
      handleEditMeetingRecord(row) {
        this.meetingForm = { ...row }
        // 处理附件列表回显
        if (row.attachmentIds) {
          this.meetingAttachmentList = row.attachmentIds
            .split(',')
            .map((id) => ({
              id,
              fileName: row.attachmentName,
              status: 'success',
            }))
        } else {
          this.meetingAttachmentList = []
        }
        this.meetingDialogVisible = true
      },
      handleDeleteMeetingRecord(row) {},
      handleViewMeetingRecord(row) {
        this.meetingForm = { ...row }
        if (row.attachmentIds) {
          this.meetingAttachmentList = row.attachmentIds
            .split(',')
            .map((id) => ({
              id,
              fileName: row.attachmentName,
              status: 'success',
            }))
        } else {
          this.meetingAttachmentList = []
        }
        this.meetingDialogVisible = true
      },
      // 查看附件
      viewMeetingAttachment(row) {
        if (!row || !row.attachmentIds) {
          this.$message &&
            this.$message.warning &&
            this.$message.warning('没有附件可供查看')
          return
        }
        const ids = String(row.attachmentIds)
          .split(',')
          .map((s) => s && s.trim())
          .filter(Boolean)
        if (!ids.length) {
          this.$message &&
            this.$message.warning &&
            this.$message.warning('没有附件可供查看')
          return
        }
        // 逐个打开附件下载/预览链接
        const base = (this.$file && this.$file.downloadUrl) || ''
        ids.forEach((id) => {
          const url = base ? `${base}?fileId=${encodeURIComponent(id)}` : ''
          if (url) window.open(url, '_blank')
        })
      },
      // 统一处理分页变更（来自子组件 CostAuditTable 的 pagination-change 事件）
      onPaginationChange({ currentPage, pageSize }) {
        if (typeof currentPage === 'number') {
          this.pagination.currentPage = currentPage
        }
        if (typeof pageSize === 'number') {
          this.pagination.pageSize = pageSize
        }
        // 保持与上次查询方式一致
        if (this.lastQuery.mode === 'task' && this.lastQuery.id) {
          this.loadRecordsByTask(this.lastQuery.id)
        } else {
          this.getMeetingRecords()
        }
      },
      // 分页大小变化
      handlePageSizeChange(pageSize) {
        this.pagination.pageSize = pageSize
        this.pagination.currentPage = 1
        // 保持与上次查询方式一致
        if (this.lastQuery.mode === 'task' && this.lastQuery.id) {
          this.loadRecordsByTask(this.lastQuery.id)
        } else {
          this.getMeetingRecords()
        }
      },
      // 当前页码变化
      handleCurrentChange(currentPage) {
        this.pagination.currentPage = currentPage
        // 保持与上次查询方式一致
        if (this.lastQuery.mode === 'task' && this.lastQuery.id) {
          this.loadRecordsByTask(this.lastQuery.id)
        } else {
          this.getMeetingRecords()
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/costAudit.scss';
</style>
