<template>
  <div class="qc-task-container">
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">{{ t('home.taskCenter.qc.title') }}</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form" label-width="130px">
        <el-form-item :label="t('home.taskCenter.qc.search.taskName')">
          <el-input
            v-model="queryParams.taskName"
            :placeholder="t('home.taskCenter.qc.search.taskNamePlaceholder')"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.qc.search.projectName')">
          <el-input
            v-model="queryParams.projectName"
            :placeholder="t('home.taskCenter.qc.search.projectNamePlaceholder')"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.qc.search.documentName')">
          <el-input
            v-model="queryParams.documentName"
            :placeholder="t('home.taskCenter.qc.search.documentNamePlaceholder')"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.qc.search.status')">
          <el-select v-model="queryParams.status" :placeholder="t('home.taskCenter.qc.search.statusPlaceholder')" clearable style="width: 120px">
            <el-option :label="t('home.taskCenter.qc.search.toAudit')" :value="0" />
            <el-option :label="t('home.taskCenter.qc.search.auditPass')" :value="1" />
            <el-option :label="t('home.taskCenter.qc.search.auditReject')" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">{{ t('home.taskCenter.qc.button.search') }}</el-button>
          <el-button icon="Refresh" @click="resetQuery">{{ t('home.taskCenter.qc.button.reset') }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 任务列表 -->
      <el-table v-loading="loading" :data="taskList" border style="margin-top: 10px">
        <el-table-column prop="id" :label="t('home.taskCenter.qc.table.id')" width="80" align="center" />
        <el-table-column prop="name" :label="t('home.taskCenter.qc.table.name')" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDocumentName(scope.row.name) }}
          </template>
        </el-table-column>
        <el-table-column prop="projectName" :label="t('home.taskCenter.qc.table.projectName')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="initiator" :label="t('home.taskCenter.qc.table.initiator')" width="120" align="center" />
        <el-table-column prop="executor" :label="t('home.taskCenter.qc.table.executor')" width="120" align="center" />
        <el-table-column prop="status" :label="t('home.taskCenter.qc.table.status')" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0 || scope.row.status === 3" type="info">{{ t('home.taskCenter.qc.table.statusToAudit') }}</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">{{ t('home.taskCenter.qc.table.statusPass') }}</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">{{ t('home.taskCenter.qc.table.statusReject') }}</el-tag>
            <el-tag v-else type="warning">{{ t('home.taskCenter.qc.table.statusUnknown') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="note" :label="t('home.taskCenter.qc.table.note')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="executeTime" :label="t('home.taskCenter.qc.table.executeTime')" width="180" align="center">
          <template #default="scope">
            <span v-if="scope.row.executeTime">{{ scope.row.executeTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="t('home.taskCenter.qc.table.createTime')" width="180" align="center">
          <template #default="scope">
            <span v-if="scope.row.createTime">{{ scope.row.createTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column
          :label="t('home.taskCenter.qc.table.action')"
          width="280"
          align="center"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 2"
              v-hasPermi="['taskCenter:qc:submit']"
              type="primary"
              icon="Upload"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleSubmit(scope.row)"
            >
              {{ t('home.taskCenter.qc.button.submit') }}
            </el-button>
            <el-button
              v-if="scope.row.status === 0 || scope.row.status === 3"
              v-hasPermi="['taskCenter:qc:audit']"
              type="success"
              icon="Check"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleAudit(scope.row)"
            >
              {{ t('home.taskCenter.qc.button.audit') }}
            </el-button>
            <el-button
              v-hasPermi="['taskCenter:qc:logAudit']"
              type="warning"
              icon="Document"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleViewLog(scope.row)"
            >
              {{ t('home.taskCenter.qc.button.viewLog') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getTaskList"
      />
    </el-card>

    <!-- 递交文档对话框 -->
    <el-dialog v-model="submitDialog.visible" :title="submitDialog.title" width="500px" append-to-body>
      <el-alert :title="t('home.taskCenter.qc.submitDialog.uploadTip')" type="info" :closable="false" style="margin-bottom: 20px" />
      <el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="100px">
        <el-form-item :label="t('home.taskCenter.qc.submitDialog.file')" prop="document">
          <fileUpload v-model="submitForm.document" :limit="1" :file-type="['pdf']" :is-show-tip="false" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSubmit">{{ t('home.taskCenter.qc.submitDialog.cancel') }}</el-button>
          <el-button type="primary" :loading="submitButtonLoading" @click="submitSubmitForm">{{
            t('home.taskCenter.qc.submitDialog.confirm')
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <QcAuditDialog
      v-model="auditDialog.visible"
      :task-detail="currentTask"
      :qc-question-type="qc_question_type"
      :dealer-search-method="handleDealerSearch"
      @submit="handleAuditSubmit"
    />

    <!-- 审核记录弹窗 -->
    <QcLogDialog v-model="logDialogVisible" :detail-id="currentLogDetailId" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, toRefs, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import type { FormInstance } from 'element-plus';
import { listQcTasks, submitQcTask, auditQcTask } from '@/api/home/taskCenter/qc';
import { QcTaskVO, QcTaskQuery, QcTaskSubmitForm, QcTaskAuditForm } from '@/api/home/taskCenter/qc/types';
import { queryMemberNotInCenter } from '@/api/project/management';
import { MemberNotInCenterVO, MemberNotInCenterQuery } from '@/api/project/management/types';
import { parseI18nName } from '@/utils/i18n';
import { formatDocumentName } from '@/utils/ruoyi';
import fileUpload from '@/components/FileUpload/index.vue';
import QcLogDialog from '@/components/QcLogDialog/index.vue';
import QcAuditDialog from '@/components/QcAuditDialog/index.vue';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as any;
const { qc_question_type } = toRefs<any>(proxy?.useDict('qc_question_type'));

const loading = ref(false);
const submitButtonLoading = ref(false);

// 当前任务
const currentTask = ref<QcTaskVO | null>(null);

// 查询参数
const queryParams = reactive<QcTaskQuery>({
  taskName: '',
  projectName: '',
  documentName: '',
  status: undefined,
  pageNum: 1,
  pageSize: 10
});

// 任务列表数据
const taskList = ref<QcTaskVO[]>([]);
const total = ref(0);

// 递交对话框
const submitDialog = reactive({
  visible: false,
  title: ''
});

// 递交表单ref
const submitFormRef = ref<FormInstance>();

// 递交表单数据
const submitForm = ref({
  document: ''
});

// 递交表单验证规则
const submitRules = {
  document: [{ required: true, message: t('home.taskCenter.qc.rule.fileRequired'), trigger: 'change' }]
};

// 审核相关
const auditDialog = reactive({
  visible: false
});

// 审核记录相关
const logDialogVisible = ref(false);
const currentLogDetailId = ref<number | undefined>(undefined);

/**
 * 获取任务列表
 */
const getTaskList = async () => {
  try {
    loading.value = true;
    const res = await listQcTasks(queryParams);
    if (res.code === 200) {
      taskList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || t('home.taskCenter.qc.message.getListFailed'));
    }
  } catch (error) {
    console.error(t('home.taskCenter.qc.message.getListFailed'), error);
    ElMessage.error(t('home.taskCenter.qc.message.getListFailed'));
  } finally {
    loading.value = false;
  }
};

/**
 * 处理搜索
 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getTaskList();
};

/**
 * 重置搜索
 */
const resetQuery = () => {
  queryParams.taskName = '';
  queryParams.projectName = '';
  queryParams.documentName = '';
  queryParams.status = undefined;
  handleQuery();
};

/**
 * 处理递交
 */
const handleSubmit = (row: QcTaskVO) => {
  currentTask.value = row;
  submitForm.value = {
    document: ''
  };
  submitDialog.visible = true;
  submitDialog.title = t('home.taskCenter.qc.submitDialog.title');
  nextTick(() => {
    submitFormRef.value?.clearValidate();
  });
};

/**
 * 取消递交
 */
const cancelSubmit = () => {
  submitDialog.visible = false;
  submitForm.value = {
    document: ''
  };
  currentTask.value = null;
};

/**
 * 提交递交表单
 */
const submitSubmitForm = () => {
  submitFormRef.value?.validate(async (valid: boolean) => {
    if (valid && currentTask.value) {
      submitButtonLoading.value = true;
      try {
        const submitData: QcTaskSubmitForm = {
          detailId: currentTask.value.id,
          document: Number(submitForm.value.document)
        };
        await submitQcTask(submitData);
        ElMessage.success(t('home.taskCenter.qc.message.submitSuccess'));
        submitDialog.visible = false;
        await getTaskList();
      } catch (error) {
        console.error(t('home.taskCenter.qc.message.submitFailed'), error);
        ElMessage.error(t('home.taskCenter.qc.message.submitFailed'));
      } finally {
        submitButtonLoading.value = false;
      }
    }
  });
};

/** 审核任务 */
const handleAudit = (row: QcTaskVO) => {
  currentTask.value = {
    ...row,
    actualDocument: row.actualDocument
  };
  auditDialog.visible = true;
};

/** 搜索处理人 - 提供给 QcAuditDialog 组件 */
const handleDealerSearch = async (query: string): Promise<any[]> => {
  try {
    const queryParams: MemberNotInCenterQuery = {
      pageNum: 1,
      pageSize: 10,
      projectId: currentTask.value?.projectId || 0,
      folderId: 0,
      name: query
    };
    const res = await queryMemberNotInCenter(queryParams);
    return res.rows || [];
  } catch (error) {
    console.error(t('home.taskCenter.qc.message.searchDealerFailed'), error);
    ElMessage.error(t('home.taskCenter.qc.message.searchDealerFailed'));
    return [];
  }
};

/** 处理审核提交 */
const handleAuditSubmit = async (formData: any) => {
  try {
    const submitData: QcTaskAuditForm = {
      taskId: currentTask.value?.taskId || 0,
      detailId: currentTask.value?.id || 0,
      result: formData.result
    };

    // 驳回时添加额外字段
    if (formData.result === 2) {
      submitData.rejectionType = formData.rejectionType;
      submitData.opinion = formData.opinion;
      submitData.designatedDealer = formData.designatedDealer;
      submitData.deadline = formData.deadline;
    }

    await auditQcTask(submitData);
    ElMessage.success(t('home.taskCenter.qc.message.auditSuccess'));
    auditDialog.visible = false;
    await getTaskList();
  } catch (error) {
    console.error(t('home.taskCenter.qc.message.auditFailed'), error);
    ElMessage.error(t('home.taskCenter.qc.message.auditFailed'));
  }
};

/** 查看审核记录 */
const handleViewLog = (row: QcTaskVO) => {
  currentLogDetailId.value = row.id;
  logDialogVisible.value = true;
};

onMounted(() => {
  getTaskList();
});
</script>

<style scoped lang="scss">
.qc-task-container {
  padding: 20px;

  .flex {
    display: flex;
  }

  .justify-between {
    justify-content: space-between;
  }

  .items-center {
    align-items: center;
  }

  .text-lg {
    font-size: 1.125rem;
  }

  .font-bold {
    font-weight: 700;
  }

  .search-form {
    margin-bottom: 15px;
  }

  :deep(.el-table) {
    .cell {
      white-space: nowrap;
    }
  }
}
</style>
