<template>
  <div class="p-2">
    <!-- 列表视图 -->
    <TaskList v-if="currentView === 'list'" @add="handleAdd" @view="handleView" />

    <!-- 详情视图 -->
    <TaskDetail v-else-if="currentView === 'detail'" :taskId="currentTaskId" @back="handleBack" />

    <!-- 添加或修改文档质控任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="发起人" prop="initiator">
          <el-input v-model="initiatorName" placeholder="请选择发起人" readonly @click="handleSelectInitiator"
            style="cursor: pointer">
            <template #suffix>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="质控项目" prop="projectId">
          <el-select v-model="form.projectId" filterable remote reserve-keyword placeholder="请输入项目名称搜索"
            :remote-method="remoteSearchProject" :loading="projectLoading" style="width: 100%">
            <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="占比" prop="proportion">
          <el-input-number v-model="form.proportion" :min="0" :precision="0" :step="1" placeholder="请输入占比（整数）"
            style="width: 100%" controls-position="right" />
        </el-form-item>

        <!-- 质控任务列表（仅修改时显示） -->
        <el-form-item v-if="form.id && taskDetailList.length > 0" label="质控任务">
          <el-table :data="taskDetailList" border style="width: 100%" max-height="400">
            <el-table-column prop="documentId" label="文档序号" width="100" align="center" />
            <el-table-column prop="documentName" label="文档名称" min-width="150" />
            <el-table-column label="质控人" width="150" align="center">
              <template #default="scope">
                <span :style="{ color: scope.row.executorStatus && scope.row.executorStatus !== '0' ? 'red' : '' }">
                  {{ scope.row.executorName }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.executorStatus" :type="scope.row.executorStatus === '0' ? 'success' : 'danger'">
                  {{ getUserStatusText(scope.row.executorStatus) }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button v-if="scope.row.executorStatus && scope.row.executorStatus !== '0'" type="warning"
                  icon="RefreshRight"
                  style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
                  @click="handleChangeExecutor(scope.row)">
                  更换质控人
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker clearable v-model="form.deadline" type="date" value-format="YYYY-MM-DD" placeholder="请选择截止时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更换质控人对话框 -->
    <UserSelect ref="userSelectRef" :multiple="false" @confirm-call-back="handleUserSelectCallback" />

    <!-- 选择发起人对话框 -->
    <UserSelect ref="initiatorSelectRef" :multiple="false" @confirm-call-back="handleInitiatorSelectCallback" />
  </div>
</template>

<script setup name="Task" lang="ts">
import { addTask, updateTask, generateTaskDetail, getTask } from '@/api/qc/task';
import { TaskVO, TaskForm, TaskDetailVO } from '@/api/qc/task/types';
import { getProjectByName } from '@/api/project/management';
import { useUserStore } from '@/store/modules/user';
import UserSelect from '@/components/UserSelect/index.vue';
import { UserVO } from '@/api/system/user/types';
import TaskList from './list.vue';
import TaskDetail from './detail.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();

// 视图状态管理
const currentView = ref('list'); // 'list' 或 'detail'
const currentTaskId = ref<string | number>();

const buttonLoading = ref(false);

// 项目列表
const projectList = ref<Array<{ id: number; name: string }>>([]);
const projectLoading = ref(false);

// 质控任务详情列表
const taskDetailList = ref<TaskDetailVO[]>([]);
// 当前选中要更换质控人的任务详情
const currentTaskDetail = ref<TaskDetailVO | null>(null);

// 用户选择组件引用
const userSelectRef = ref<InstanceType<typeof UserSelect>>();
const initiatorSelectRef = ref<InstanceType<typeof UserSelect>>();

// 发起人昵称（用于显示）
const initiatorName = ref<string>('');

const taskFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 用户状态枚举映射
const userStatusMap = {
  '0': '正常',
  '1': '停用',
  '2': '删除'
};

/** 获取用户状态文本 */
const getUserStatusText = (status: string) => {
  return userStatusMap[status] || '未知';
};

const initFormData: TaskForm = {
  id: undefined,
  name: undefined,
  initiator: undefined,
  projectId: undefined,
  proportion: undefined,
  deadline: undefined,
  status: undefined,
  note: undefined
};
const data = reactive<PageData<TaskForm, any>>({
  form: { ...initFormData },
  rules: {
    name: [{ required: true, message: '质控名称不能为空', trigger: 'blur' }],
    initiator: [{ required: true, message: '发起人不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '质控项目不能为空', trigger: 'change' }],
    proportion: [
      { required: true, message: '占比不能为空', trigger: 'blur' },
      { type: 'number', message: '占比必须为数字', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value !== undefined && value !== null && value !== '') {
            if (!Number.isInteger(Number(value))) {
              callback(new Error('占比必须为整数'));
            } else if (value < 0) {
              callback(new Error('占比不能为负数'));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],

    deadline: [{ required: true, message: '截止时间不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { form, rules } = toRefs(data);

/** 远程搜索项目 */
const remoteSearchProject = async (query: string) => {
  if (query) {
    projectLoading.value = true;
    try {
      const res = await getProjectByName(query);
      projectList.value = res.data || [];
    } catch (error) {
      console.error('搜索项目失败:', error);
      projectList.value = [];
    } finally {
      projectLoading.value = false;
    }
  } else {
    projectList.value = [];
  }
};

/** 项目选择变化时加载质控任务详情（仅修改时） */
const handleProjectChange = async (projectId: number) => {
  // 新增时不加载质控任务详情
  if (!form.value.id) {
    return;
  }

  if (!projectId) {
    taskDetailList.value = [];
    return;
  }

  try {
    const res = await generateTaskDetail(projectId);
    if (res.code === 200 && res.data) {
      taskDetailList.value = res.data;
    } else {
      taskDetailList.value = [];
      proxy?.$modal.msgWarning('获取质控任务详情失败');
    }
  } catch (error) {
    console.error('获取质控任务详情失败:', error);
    taskDetailList.value = [];
    proxy?.$modal.msgError('获取质控任务详情失败');
  }
};

/** 更换质控人 */
const handleChangeExecutor = (row: TaskDetailVO) => {
  currentTaskDetail.value = row;
  userSelectRef.value?.open();
};

/** 用户选择回调 */
const handleUserSelectCallback = (users: UserVO[]) => {
  if (users && users.length > 0 && currentTaskDetail.value) {
    const selectedUser = users[0];
    currentTaskDetail.value.executor = selectedUser.userId;
    currentTaskDetail.value.executorName = selectedUser.nickName || selectedUser.userName;
    currentTaskDetail.value.executorStatus = '0'; // 新选择的用户状态为正常
    proxy?.$modal.msgSuccess('更换质控人成功');
  }
};

/** 选择发起人 */
const handleSelectInitiator = () => {
  initiatorSelectRef.value?.open();
};

/** 发起人选择回调 */
const handleInitiatorSelectCallback = (users: UserVO[]) => {
  if (users && users.length > 0) {
    const selectedUser = users[0];
    form.value.initiator = selectedUser.userId;
    initiatorName.value = selectedUser.nickName || selectedUser.userName;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  projectList.value = [];
  taskDetailList.value = [];
  currentTaskDetail.value = null;
  initiatorName.value = '';
  taskFormRef.value?.resetFields();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 设置默认发起人为当前用户
  form.value.initiator = userStore.userId;
  initiatorName.value = userStore.nickname || userStore.name;
  dialog.visible = true;
  dialog.title = '添加文档质控任务';
};

/** 查看任务详情 */
const handleView = (taskId: string | number) => {
  currentTaskId.value = taskId;
  currentView.value = 'detail';
};

/** 返回列表 */
const handleBack = () => {
  currentView.value = 'list';
  currentTaskId.value = undefined;
};

/** 修改按钮操作 */
const handleUpdate = async (row: TaskVO) => {
  reset();
  const res = await getTask(row.id);
  Object.assign(form.value, res.data);

  // 设置发起人昵称
  if (res.data.initiatorName) {
    initiatorName.value = res.data.initiatorName;
  } else if (res.data.initiator) {
    // 如果后端没有返回昵称，使用ID作为显示（或者可以调用接口获取）
    initiatorName.value = String(res.data.initiator);
  }

  // 如果有项目ID，加载项目信息到下拉列表
  if (form.value.projectId) {
    try {
      const projectRes = await getProjectByName('');
      projectList.value = projectRes.data || [];
    } catch (error) {
      console.error('加载项目信息失败:', error);
    }
  }

  // 直接使用返回的 details 数据
  if (res.data.details && res.data.details.length > 0) {
    taskDetailList.value = res.data.details;
  }

  dialog.visible = true;
  dialog.title = '修改文档质控任务';
};

/** 提交按钮 */
const submitForm = () => {
  taskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      // 构建提交数据
      const submitData: any = {
        ...form.value
      };

      // 仅修改时才包含 details
      if (form.value.id && taskDetailList.value.length > 0) {
        submitData.details = taskDetailList.value.map((item) => ({
          id: item.id,
          taskId: item.taskId || form.value.id,
          documentId: item.documentId,
          executor: item.executor,
          projectId: form.value.projectId,
          status: item.status,
          note: item.note,
          createDept: item.createDept || form.value.createDept,
          createBy: item.createBy || form.value.createBy,
          createTime: item.createTime || form.value.createTime,
          updateBy: item.updateBy || form.value.updateBy,
          updateTime: item.updateTime || form.value.updateTime,
          params: item.params || {}
        }));
      }

      if (form.value.id) {
        await updateTask(submitData).finally(() => (buttonLoading.value = false));
      } else {
        await addTask(submitData).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
    }
  });
};
</script>
