<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- <el-form-item label="项目ID" prop="projectId">
              <el-input v-model="queryParams.projectId" placeholder="请输入项目ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['design:drawingreview:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['design:drawingreview:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['design:drawingreview:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['design:drawingreview:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="drawingreviewList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目ID" align="center" prop="id" v-if="true" />
        <el-table-column label="文件名称" align="center" prop="fileName" />
        <el-table-column label="审核类型" align="center" prop="auditType" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['design:drawingreview:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['design:drawingreview:remove']"></el-button>
            </el-tooltip> -->
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleExamine(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设计-图纸评审对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="drawingreviewFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="审核类型" prop="auditType">
          <el-upload ref="uploadRef" class="upload-demo" :http-request="importExcel">
            <template #trigger>
              <el-button type="primary">上传excel</el-button>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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>
    <!-- 审核 -->
    <el-dialog title="审核" v-model="examineDialog" width="500px" append-to-body>
      <el-form ref="formRef" :model="examineForm" :rules="rules1" label-width="120px" class="info-form">
        <!-- 基本信息区域 -->
        <el-form-item label="编号" prop="num">
          <el-input v-model="examineForm.num" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="专业" prop="professional">
          <el-input v-model="examineForm.professional" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="设计阶段" prop="stage">
          <el-input v-model="examineForm.stage" placeholder="请输入设计阶段" />
        </el-form-item>
        <el-form-item label="卷册" prop="volume">
          <el-input v-model="examineForm.volume" placeholder="请输入卷册" />
        </el-form-item>

        <!-- 项目信息区域 -->
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="examineForm.projectId" placeholder="请输入项目ID" />
        </el-form-item>

        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="examineForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>

        <el-form-item label="子项目ID" prop="subprojectId">
          <el-input v-model="examineForm.subprojectId" placeholder="请输入子项目ID" />
        </el-form-item>

        <el-form-item label="子项目名称" prop="subprojectName">
          <el-input v-model="examineForm.subprojectName" placeholder="请输入子项目名称" />
        </el-form-item>

        <!-- 人员信息区域 -->
        <el-form-item label="设计人" prop="designer">
          <el-input v-model="examineForm.designer" placeholder="请输入设计人" />
        </el-form-item>

        <el-form-item label="校审人员" prop="proofreading">
          <el-input v-model="examineForm.proofreading" placeholder="请输入校审人员" />
        </el-form-item>

        <el-form-item label="校审人员ID" prop="proofreadingId">
          <el-input v-model="examineForm.proofreadingId" placeholder="请输入校审人员ID" />
        </el-form-item>

        <el-form-item label="校审时间" prop="proofreadingDate">
          <el-date-picker v-model="examineForm.proofreadingDate" type="datetime" placeholder="选择校审时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <el-form-item label="审核人员" prop="audit">
          <el-input v-model="examineForm.audit" placeholder="请输入审核人员" />
        </el-form-item>

        <el-form-item label="审核人员ID" prop="auditId">
          <el-input v-model="examineForm.auditId" placeholder="请输入审核人员ID" />
        </el-form-item>

        <el-form-item label="审核时间" prop="auditDate">
          <el-date-picker v-model="examineForm.auditDate" type="datetime" placeholder="选择审核时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <el-form-item label="执行人员" prop="executor">
          <el-input v-model="examineForm.executor" placeholder="请输入执行人员" />
        </el-form-item>

        <el-form-item label="执行人员ID" prop="executorId">
          <el-input v-model="examineForm.executorId" placeholder="请输入执行人员ID" />
        </el-form-item>

        <el-form-item label="执行时间" prop="executorDate">
          <el-date-picker v-model="examineForm.executorDate" type="datetime" placeholder="选择执行时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <!-- 意见和内容区域 -->
        <el-form-item label="验证内容" prop="verificationContent">
          <el-input v-model="examineForm.verificationContent" type="textarea" placeholder="请输入验证内容" />
        </el-form-item>

        <el-form-item label="验证意见" prop="verificationOpinion">
          <el-input v-model="examineForm.verificationOpinion" type="textarea" placeholder="请输入验证意见" />
        </el-form-item>

        <el-form-item label="执行意见" prop="executionOpinion">
          <el-input v-model="examineForm.executionOpinion" type="textarea" placeholder="请输入执行意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitexamineForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Drawingreview" lang="ts">
import { computed, getCurrentInstance } from 'vue';
import { listDrawingreview, getDrawingreview, delDrawingreview, addDrawingreview, updateDrawingreview,fillOutTheDesignVerificationForm } from '@/api/design/drawingreview';
import { DrawingreviewVO, DrawingreviewQuery, DrawingreviewForm } from '@/api/design/drawingreview/types';
import { useUserStoreHook } from '@/store/modules/user';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const drawingreviewList = ref<DrawingreviewVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const formRef = ref();
let fromData = new FormData();
const queryFormRef = ref<ElFormInstance>();
const drawingreviewFormRef = ref<ElFormInstance>();
console.log(currentProject.value);
const examineDialog = ref(false);
// 审核form
const examineForm = reactive({
  /**
   * 审核人员
   */
  audit: '',
  /**
   * 审核时间
   */
  auditDate: '',
  /**
   * 审核人员ID
   */
  auditId: '',
  /**
   * 设计人
   */
  designer: '',
  /**
   * 执行意见
   */
  executionOpinion: '',
  /**
   * 执行人员
   */
  executor: '',
  /**
   * 执行时间
   */
  executorDate: '',
  /**
   * 执行人员ID
   */
  executorId: '',
  /**
   * 主键ID
   */
  id: '1',
  /**
   * 编号
   */
  num: '',
  /**
   * 专业
   */
  professional: '',
  /**
   * 项目ID
   */
  projectId: '',
  /**
   * 项目名称
   */
  projectName: '',
  /**
   * 校审人员
   */
  proofreading: '',
  /**
   * 校审时间
   */
  proofreadingDate: '',
  /**
   * 校审人员ID
   */
  proofreadingId: '',
  /**
   * 设计阶段
   */
  stage: '',
  /**
   * 子项目ID
   */
  subprojectId: '',
  /**
   * 子项目名称
   */
  subprojectName: '',
  /**
   * 验证内容
   */
  verificationContent: '',
  /**
   * 验证意见
   */
  verificationOpinion: '',
  /**
   * 卷册
   */
  volume: ''
});
const rules1 = reactive({
  num: [
    { required: true, message: '请输入编号', trigger: 'blur' },
    { max: 50, message: '编号长度不能超过50个字符', trigger: 'blur' }
  ],
  professional: [
    { required: true, message: '请输入专业', trigger: 'blur' },
    { max: 100, message: '专业长度不能超过100个字符', trigger: 'blur' }
  ],
  stage: [
    { required: true, message: '请输入设计阶段', trigger: 'blur' },
    { max: 100, message: '设计阶段长度不能超过100个字符', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请输入项目ID', trigger: 'blur' },
    { max: 50, message: '项目ID长度不能超过50个字符', trigger: 'blur' }
  ],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 200, message: '项目名称长度不能超过200个字符', trigger: 'blur' }
  ],
  designer: [
    { required: true, message: '请输入设计人', trigger: 'blur' },
    { max: 50, message: '设计人长度不能超过50个字符', trigger: 'blur' }
  ],
  verificationContent: [
    { required: true, message: '请输入验证内容', trigger: 'blur' },
    { max: 2000, message: '验证内容长度不能超过2000个字符', trigger: 'blur' }
  ],
  // 其他字段的验证规则
  volume: [
    { max: 100, message: '卷册长度不能超过100个字符', trigger: 'blur' }
  ],
  subprojectId: [
    { max: 50, message: '子项目ID长度不能超过50个字符', trigger: 'blur' }
  ],
  subprojectName: [
    { max: 200, message: '子项目名称长度不能超过200个字符', trigger: 'blur' }
  ],
  proofreading: [
    { max: 50, message: '校审人员长度不能超过50个字符', trigger: 'blur' }
  ],
  proofreadingId: [
    { max: 50, message: '校审人员ID长度不能超过50个字符', trigger: 'blur' }
  ],
  audit: [
    { max: 50, message: '审核人员长度不能超过50个字符', trigger: 'blur' }
  ],
  auditId: [
    { max: 50, message: '审核人员ID长度不能超过50个字符', trigger: 'blur' }
  ],
  executor: [
    { max: 50, message: '执行人员长度不能超过50个字符', trigger: 'blur' }
  ],
  executorId: [
    { max: 50, message: '执行人员ID长度不能超过50个字符', trigger: 'blur' }
  ],
  verificationOpinion: [
    { max: 2000, message: '验证意见长度不能超过2000个字符', trigger: 'blur' }
  ],
  executionOpinion: [
    { max: 2000, message: '执行意见长度不能超过2000个字符', trigger: 'blur' }
  ]
});

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

const initexamineForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  auditType: undefined,
  remark: undefined,
}
const data = reactive({
  form: { ...initexamineForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    auditType: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "项目ID不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询设计-图纸评审列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDrawingreview(queryParams.value);
  drawingreviewList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initexamineForm };
  drawingreviewFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DrawingreviewVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加设计-图纸评审";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DrawingreviewVO) => {
  reset();
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = "修改设计-图纸评审";
}

/** 提交按钮 */
const submitForm = () => {
  drawingreviewFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDrawingreview(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addDrawingreview(form.value, examineForm).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DrawingreviewVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设计-图纸评审编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delDrawingreview(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('design/drawingreview/export', {
    ...queryParams.value
  }, `drawingreview_${new Date().getTime()}.xlsx`)
}

// 上传excel
function importExcel(options) {
  fromData.append("file", options.file)
}
// 审核
function handleExamine(item) {
  examineDialog.value = true;
  examineForm.id = item.id
  console.log(item.id)
}
// 设计验证表
async function submitexamineForm() {
  try {
    await formRef.value.validate();
    fillOutTheDesignVerificationForm(examineForm).then((res) => {
      console.log(res);
    })
    // 表单验证通过，可以提交数据
    ElMessage.success('表单提交成功');
    // 这里可以添加实际提交数据的逻辑，例如调用API
    console.log('表单数据:', examineForm);
  } catch (error) {
    ElMessage.error('表单验证失败，请检查输入');
    console.error('表单验证错误:', error);
  }
}

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