<template>
  <div class="app-container">
    <div ref="topContainerRef">
      <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        label-width="100px"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
      >
        <template #one>
          <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                v-model="queryParams.projectName"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
            <el-form-item label="测试人员" prop="tester">
              <el-input
                v-model="queryParams.tester"
                placeholder="请输入测试人员"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
        </template>
      </TableSearch>

      <el-row :gutter="10" class="mb8">
        <el-col>
          <el-button
            type="primary"
            plain
            icon="Plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:project:add']"
            >新增</el-button
          >
        </el-col>
      </el-row>
    </div>

    <div :style="containerHeight">
      <el-table
        v-loading="loading"
        height="100%"
        :data="projectList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="项目ID"
          align="center"
          prop="projectId"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="项目名称"
          align="center"
          prop="projectName"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="车机版本Id"
          align="center"
          prop="vehicleConfigId"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column label="测试人员" align="center" prop="tester" />
        <el-table-column
          label="计划测试开始时间"
          align="center"
          prop="planStart"
          width="180"
        >
          <template #default="{ row }">
            <span>{{ parseTime(row.planStart) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="计划测试结束时间"
          align="center"
          prop="planEnd"
          width="180"
        >
          <template #default="{ row }">
            <span>{{ parseTime(row.planEnd) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="项目描述"
          width="200"
          show-overflow-tooltip
          align="center"
          prop="remark"
        />
        <el-table-column label="项目状态" align="center" prop="status">
          <template #default="{ row }">
            {{ row.status == '0' ? "未执行" :  row.status == '1' ? "执行中" : "已完成" }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="320px"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              size="mini"
              type="text"
              v-if="row.status == '0'"
              @click="handleExecute(row)"
              >执行
            </el-button>
            <el-button
              v-if="row.status == '2'"
              size="mini"
              type="text"
              @click="handleEvaluate(row)"
              >评价
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(row)"
              v-if="row.status != '1'"
              v-hasPermi="['system:project:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(row)"
              v-if="row.status != '1'"
              v-hasPermi="['system:project:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      :title="title"
      v-model="open"
      width="740px"
      :append-to-body="false"
      body-class="testProject_dialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <div class="card">
          <div class="form-title">项目信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="form.projectName" placeholder="请输入语料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车机版本" prop="vehicleConfigId">
                <el-tree-select
                  v-model="form.vehicleConfigId"
                  node-key="id"
                  :data="treeData"
                  :render-after-expand="false"
                  style="width: 240px"
                  @change="vehicleConfigChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="功能选择" prop="testFuncIds">
                <el-select
                  v-model="form.testFuncIds"
                  :multiple="true"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in funcIdOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="测试人员" prop="tester">
                <el-input v-model="form.tester" placeholder="请输入测试人员" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划开始时间" prop="planStart">
                <el-date-picker
                  clearable
                  v-model="form.planStart"
                  type="datetime"
                  placeholder="请选择计划测试开始时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划结束时间" prop="planEnd">
                <el-date-picker
                  clearable
                  v-model="form.planEnd"
                  type="datetime"
                  placeholder="请选择计划测试结束时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" placeholder="排序" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="评价指标" prop="indicatorId">
                  <el-tree-select
                    v-model="form.indicatorId"
                    :data="indicatorData"
                    :props="{ label: 'name', value: 'id', children: 'children' }"
                    :render-after-expand="false"
                  />
                </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目描述" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入项目描述"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="card">
          <div class="form-title">样品信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="样品名称" prop="sampleName">
                <el-input v-model="form.sampleName" placeholder="请输入语料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商标" prop="trademark">
                <el-input v-model="form.trademark" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号规格" prop="modelSpec">
                <el-input v-model="form.modelSpec" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="样品数量" prop="quantity">
                <el-input-number
                  v-model="form.quantity"
                  :min="1"
                  :step="1"
                  :step-strictly="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="委托单位" prop="entrustUnit">
                <el-input v-model="form.entrustUnit" placeholder="请输入委托单位" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产单位" prop="productionUnit">
                <el-input v-model="form.productionUnit" placeholder="请输入生产单位" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="送样日期" prop="sampleDate">
                <el-date-picker
                  clearable
                  v-model="form.sampleDate"
                  type="datetime"
                  placeholder="请选择送样日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker
                  clearable
                  v-model="form.productionDate"
                  type="datetime"
                  placeholder="请选择生产日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

      <Run
        :drawer="executeOpen"
        @close="closeRun"
        :projectId="executeProjectId"
        :functionIds="functionIds"
      />
  </div>
</template>

<script setup>
import TableSearch from "@/components/TableSearch/index.vue";
import { useContainerHeight } from "@/hooks/tableHeight";
import { ElMessage, ElMessageBox } from "element-plus";
import { getTreeDataApi } from '@/api/is/func/index'
import { getChildrenByParentIdWithLevelLimitApi } from "@/api/evaluate/indicator.js";
import { getFunction } from "@/api/is/func/index.js";
import { addProject, getProjectList, updateProject, deleteProject } from "@/api/is/project/index.js";
import Run from "@/views/is/project/evaluate/Run.vue";

const topContainerRef = ref();
const containerHeight = useContainerHeight(topContainerRef);

const projectList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    projectName: null,
    tester: null,
    planStart: null,
    vehicleConfigId: null,
    testFuncIds: null,
    indicatorId: null,
    planEnd: null,
    sort: null,
    remark: null,
    status: null,
    sampleName: null,
    trademark: null,
    modelSpec: null,
    quantity: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    tester: [{ required: true, message: "请输入测试人员", trigger: "blur" }],
    planStart: [{ required: true, message: "请输入计划测试开始时间", trigger: "blur" }],
    planEnd: [{ required: true, message: "请输入计划测试结束时间", trigger: "blur" }],
    vehicleConfigId: [{ required: true, message: "请选择车机版本", trigger: "blur" }],
    testFuncIds: [{ required: true, message: "请选择功能", trigger: "blur" }],
    indicatorId: [{ required: true, message: "请选择评价指标", trigger: "blur" }],
    sampleName: [{ required: true, message: "请输入样品名称", trigger: "blur" }],
    trademark: [{ required: true, message: "请输入样品商标", trigger: "blur" }],
    modelSpec: [{ required: true, message: "请输入样品型号规格", trigger: "blur" }],
    entrustUnit: [{ required: true, message: "请输入样品委托单位", trigger: "blur" }],
    productionUnit: [{ required: true, message: "请输入样品生产单位", trigger: "blur" }],
    quantity: [
      { required: true, message: "请输入样品数量" },
      { type: 'number', message: '请输入样品数量' },],
    sampleDate: [{ required: true, message: "请输入样品送达日期", trigger: "blur" }],
    productionDate: [{ required: true, message: "请输入样品生产日期", trigger: "blur" }],
  },
});

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

const treeData = ref([])

const getTreeData = async () => {
  try {
    const res = await getTreeDataApi();
    if (res) {
      treeData.value = res;
    }
  } catch (err) {
    console.error("获取树数据异常：", err);
    ElMessage.error("加载车机版本树失败");
  }
}

/** 查询语音交互-项目列表 */
function getList() {
  getProjectList(queryParams.value)
    .then(res => {
      if (res.code === 200) {
        projectList.value = res.rows;
        total.value = res.total;
        let status = 0;
        for (let i = 0; i < projectList.value.length; i++) {
          if (projectList.value[i].status == '1') {
            status = 1;
            break;
          }
        }
        if (status == 1) {
          // 如果有正在执行的项目，则每5秒刷新一次列表
          setTimeout(() => {
            getList();
          }, 5000);
        }
      } else {
        ElMessage.error(res.msg || "查询项目列表失败");
      }
    })
    .catch(err => {
      console.error("查询项目列表异常：", err);
      ElMessage.error("网络异常，查询项目列表失败");
    })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    projectId: null,
    projectName: null,
    tester: null,
    planStart: null,
    planEnd: null,
    vehicleConfigId: null,
    testFuncIds: null,
    indicatorId: null,
    sort: null,
    remark: null,
    status: null,
    sampleName: null,
    trademark: null,
    modelSpec: null,
    quantity: null,
    status: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const isAdd = ref(false);
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  isAdd.value = true;
  title.value = "添加测试项目";
}


const formRef = ref();
const submitForm = () => {
  if (!formRef.value) return;

  formRef.value.validate((valid) => {
    if (!valid) {
      return
    }
    form.value.testFuncIds = JSON.stringify(form.value.testFuncIds)
    if (isAdd.value) {
     addProject(form.value).then(res => {
        if (res.code === 200) {
          ElMessage.success("添加成功");
          getList();
        }
      })
    } else {
      updateProject(form.value).then(res => {
        if (res.code === 200) {
          ElMessage.success("修改成功");
          getList();
        }
      })
    }
    open.value = false;
    reset();
  });
};

const handleUpdate = (row) => {
  reset();
  open.value = true;
  isAdd.value = false;
  title.value = "修改测试项目";
  form.value = row;
  let arr = []
  try {
    arr = JSON.parse(form.value.testFuncIds);
  } catch {
    arr = []
  } finally {
    form.value.testFuncIds = arr
    getFuncList(form.value.vehicleConfigId)
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除项目"${row.projectName}"吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    deleteProject(row.projectId).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      }
    });
  });
};

const indicatorData = ref([]);
const getIndicatorData = () => {
  getChildrenByParentIdWithLevelLimitApi(0,2, 1)
    .then((res) => {
      if (res.code === 200) {
        indicatorData.value = res.data || [];
      } else {
        ElMessage.error(res.msg || "加载评价指标失败");
      }
    })
    .catch(err => {
      console.error("获取评价指标异常：", err);
      ElMessage.error("网络异常，加载评价指标失败");
    });
}
const { proxy } = getCurrentInstance()
const { ti_function_config } = proxy.useDict("ti_function_config")
const funcIdOptions = ref([])
const vehicleConfigChange = (value) => {
  form.value.testFuncIds = null
  funcIdOptions.value = []
  getFuncList(value)
}

const getFuncList = (value) => {
  getFunction({
    pageNum: 1,
    pageSize: 10000,
    vehicleConfigId: value
  }).then((res) => {
    if (res.code === 200) {
      funcIdOptions.value = (res.rows || []).map(item => {
        const label = ti_function_config.value.find(func => {
          return func.value === item.funcKey
        }).label
        return {
          label: label,
          value: item.id
        }
      })
    }
  })
}

const executeOpen = ref(false);
const executeProjectId = ref(null);
const functionIds = ref([])
const handleExecute = (row) => {
  executeOpen.value = true;
  executeProjectId.value = row.projectId;
  // 后端临时应付检查添加，后续可删除
  let arr = []
  try {
    arr = JSON.parse(row.testFuncIds);
  } catch {
    arr = []
  } finally {
    functionIds.value = arr
  }
}

const router = useRouter()
const handleEvaluate = (row) => {
  router.push({
    path: "/is/evaluate/index/" + row.projectId, // 目标路由路径
    // 对象序列化为 JSON 字符串（关键）
    query: {
      data: JSON.stringify(row)
    }
  })
}

const closeRun = () => {
  executeOpen.value = false
  getList()
}

onMounted(() => {
  getList();
  getTreeData();
  getIndicatorData();
});
</script>
<style lang="scss" scoped>
:deep() {
  .testProject_dialog {
    .el-date-editor {
      --el-date-editor-width: 100%;
    }

    .el-input-number {
      width: 100%;
    }

    .card {
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 20px;

      &:hover {
        box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
      }

      .form-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        margin-bottom: 10px;

        &::before {
          content: "";
          width: 4px;
          height: 16px;
          background: blue;
          display: inline-block;
          margin-right: 8px;
        }
      }
    }
  }

  .el-scrollbar__view {
    width: 100%;
  }
}
</style>
