<template>
  <div class="audit-task-deployment-container">
    <div v-if="activeView === 'list'">
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="年度：">
            <el-date-picker
              v-model="searchForm.projectYear"
              type="year"
              placeholder="请选择年度"
              format="yyyy"
              value-format="yyyy"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="监审项目名称：">
            <el-input
              v-model="searchForm.projectName"
              placeholder="请输入监审项目名称"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button
              plain
              type="primary"
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <CostAuditTable
          :table-data="taskList"
          :columns="tableColumns"
          :show-index="true"
          :show-pagination="true"
          :pagination="pagination"
          @pagination-change="handlePaginationChange"
        >
          <template #projectName="{ row }">
            <span class="link-text" @click="handleView(row)">
              {{ row.projectName }}
            </span>
          </template>
          <template #auditedUnitId="{ row }">
            {{ getUnitName(row.auditedUnitId) }}
          </template>
          <template #status="{ row }">
            {{ row.status | statusFilter }}
          </template>
          <template #action="{ row }">
            <el-button
              v-if="row.status != '2'"
              type="text"
              @click="handleTaskFormulate(row)"
            >
              任务制定
            </el-button>
            <el-button
              v-if="row.status != '2'"
              type="text"
              @click="handleTaskPublish(row)"
            >
              任务发布
            </el-button>
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text " @click="handleMemo(row)">备忘录</el-button>
          </template>
        </CostAuditTable>
      </div>
    </div>
    <div v-if="activeView === 'taskFormulate'">
      <taskFormulate
        :project="project"
        :is-view="isView"
        @backToList="handleBackToList"
      ></taskFormulate>
    </div>
    <!-- 任务发布弹窗 -->
    <el-dialog
      title="任务发布"
      :visible.sync="publishDialogVisible"
      width="30%"
      :before-close="handleClosePublishDialog"
    >
      <el-form
        ref="publishForm"
        :model="publishForm"
        label-width="150px"
        style="margin-top: 20px"
        :rules="publishFormRules"
      >
        <el-form-item label="被监审单位：" prop="auditedUnitName">
          <el-input
            v-model="publishForm.auditedUnitName"
            placeholder="请输入被监审单位"
            style="width: 100%"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="监审组人员：" prop="auditGroup">
          <el-select
            v-model="publishForm.auditGroup"
            placeholder="请选择成员"
            style="width: 100%"
            multiple
          >
            <el-option
              v-for="(item, index) in userList"
              :key="index"
              :label="item.fullname"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监审任务发布通知：" prop="content">
          <el-input
            v-model="publishForm.content"
            type="textarea"
            rows="6"
            placeholder="请输入监审任务发布通知"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="发送方式：" prop="sendType">
          <el-checkbox-group v-model="publishForm.sendType" style="width: 100%">
            <el-checkbox label="1" style="margin-right: 20px">
              站内消息
            </el-checkbox>
            <el-checkbox label="2">短信通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmTaskPublish">确认</el-button>
        <el-button @click="handleClosePublishDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { Message } from 'element-ui'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import taskFormulate from './tabs.vue'
  import { publishCostProjectApproval } from '@/api/auditInitiation'
  import { getAllUnitList } from '@/api/auditEntityManage'
  import { taskMixin } from './index.js'
  import { getAllUserList } from '@/api/uc'
  import {
    getData,
    getDataList,
    getDetail,
    getDetailById,
    delProjectApprovalById,
    addProjectApproval,
    editProjectApproval,
    delProjectApproval,
  } from '@/api/auditInitiation'
  export default {
    name: 'TaskCustomizedRelease',
    components: {
      CostAuditTable,
      taskFormulate,
    },
    filters: {
      statusFilter(value) {
        if (!value) return ''
        switch (value) {
          case '1':
            return '未发布'
          case '2':
            return '已发布'
          default:
            return '未知状态'
        }
      },
    },
    mixins: [taskMixin],

    data() {
      return {
        activeView: 'list',
        isView: false,
        // 搜索表单
        searchForm: {
          projectYear: '',
          projectName: '',
        },
        //被监审单位主体名称映射
        UnitNameMap: {},
        // 任务列表数据
        taskList: [],
        // 分页信息
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
        },
        project: {},
        // 任务发布弹窗相关
        publishDialogVisible: false,
        selectedTask: null,
        publishForm: {
          auditedUnit: '',
          auditTeam: '',
          noticeContent: '',
          sendType: ['1', '2'],
        },
        publishFormRules: {
          content: [
            {
              required: true,
              message: '请输入任务发布通知',
              trigger: 'blur',
            },
          ],
          sendType: [
            {
              required: true,
              message: '请选择发送方式',
              trigger: 'blur',
            },
          ],
        },
        userList: [],
        unitList: [],
      }
    },
    computed: {
      tableColumns() {
        return [
          {
            prop: 'projectYear',
            label: '立项年度',
            width: 120,
            align: 'center',
            formatter: (row) => `${row.projectYear}年`,
          },
          {
            prop: 'projectName',
            label: '成本监审项目名称',
            slotName: 'projectName',
          },
          {
            prop: 'auditedUnitId',
            label: '被监审单位',
            slotName: 'auditedUnitId',
          },
          {
            prop: 'auditPeriod',
            label: '监审期间',
            align: 'center',
          },
          {
            prop: 'sourceType',
            label: '立项来源',
            align: 'center',
            formatter: (row) => {
              return this.getDictName('projectProposal', row.sourceType)
            },
          },
          {
            prop: 'auditType',
            label: '监审形式',
            align: 'center',
            formatter: (row) => {
              return this.getDictName('auditType', row.auditType)
            },
          },
          {
            prop: 'status',
            label: '任务状态',
            width: 100,
            align: 'center',
            slotName: 'status',
          },
          {
            prop: 'action',
            label: '操作',
            width: 300,
            align: 'center',
            slotName: 'action',
          },
        ]
      },
    },
    mounted() {
      this.handleSearch()
    },
    methods: {
      // 获取用户信息
      getUser() {
        getAllUserList().then((res) => {
          this.userList = res.value || []
        })
      },
      getAllUnitList() {
        getAllUnitList().then((res) => {
          this.unitList = res.value || []
          // 过滤掉状态为停用的数据
          // this.unitList = this.unitList.filter((item) => item.status == 1)
        })
      },
      getUnitName(unitId) {
        // 直接处理unitId值，而不是row对象
        if (unitId && typeof unitId === 'string' && unitId.includes(',')) {
          // 如果包含逗号，分割成数组并查找对应的unitName
          const unitIds = unitId.split(',')
          return unitIds
            .map((id) => {
              const unit = this.unitList.find((item) => item.unitId == id)
              return unit ? unit.unitName : '无'
            })
            .filter((name) => name) // 过滤空值
            .join(',')
        } else {
          // 单个unitId的情况
          const unit = this.unitList.find((item) => item.unitId == unitId)
          return unit ? unit.unitName : '无'
        }
      },
      // 查询
      handleSearch() {
        getDataList({
          ...this.searchForm,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
        }).then((res) => {
          this.taskList = res.value.value.records
          this.pagination.total = res.value.value.total
          this.getAllUnitList()
        })
      },
      handleReset() {
        this.searchForm = {
          projectYear: '',
          projectName: '',
        }
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10

        this.handleSearch()
      },

      // 任务制定
      handleTaskFormulate(row) {
        this.activeView = 'taskFormulate'
        this.isView = false
        this.project = {
          ...row,
          auditedUnitName: this.UnitNameMap[row.auditedUnitId],
        }
      },

      // 任务发布 - 打开弹窗
      handleTaskPublish(row) {
        this.getUser()
        this.selectedTask = row
        // 初始化表单数据
        this.publishForm = {
          projectId: row.projectId || '',
          auditedUnit: row.auditedUnit || '',
          auditedUnitName: this.UnitNameMap[row.auditedUnitId] || '',
          auditGroup: row.projectMembers ? row.projectMembers.split(',') : [],
          content: `${row.projectYear}年${row.projectName}已发布，请及时办理。`,
          sendType: row.sendType ? row.sendType.split(',') : [],
        }
        this.publishDialogVisible = true
      },

      // 关闭任务发布弹窗
      handleClosePublishDialog() {
        this.publishDialogVisible = false
        this.selectedTask = null
      },

      // 确认任务发布
      confirmTaskPublish() {
        publishCostProjectApproval({
          projectId: this.publishForm.projectId,
          auditGroup: this.publishForm.auditGroup.join(','),
          content: this.publishForm.content,
          sendType: this.publishForm.sendType.join(','),
        }).then(() => {
          Message.success('任务发布成功')
          this.publishDialogVisible = false
          this.selectedTask = null
          // 刷新列表
          this.handleSearch()
        })
      },

      // 查看
      handleView(row) {
        this.activeView = 'taskFormulate'
        this.isView = true
        this.project = {
          ...row,
        }
      },

      // 备忘录
      handleMemo(row) {
        this.$router.push({
          name: 'memoManage',
          // params: { projectId: project.id }
        })
      },

      // 分页变化事件处理
      handlePaginationChange({ currentPage, pageSize }) {
        this.pagination.currentPage = currentPage
        this.pagination.pageSize = pageSize
        this.handleSearch()
      },
      handleBackToList() {
        this.activeView = 'list'
        this.isView = false
        this.handleSearch()
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
  .audit-task-deployment-container {
    padding: 20px;
  }
</style>
