<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="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目简称" prop="shortName">
              <el-input v-model="queryParams.shortName" placeholder="请输入项目简称" 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="['project:project:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['project:project:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['project:project:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['project:project:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="项目简称" align="center" prop="shortName" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="项目类型" align="center" prop="type" />
        <el-table-column label="项目类别" align="center" prop="isType">
          <template #default="scope">
            <dict-tag :options="project_category_type" :value="scope.row.isType" />
          </template>
        </el-table-column>
        <el-table-column label="项目地址" align="center" prop="projectSite" />
        <el-table-column label="负责人" align="center" prop="principal" />
        <el-table-column label="负责人电话" align="center" prop="principalPhone" />
        <el-table-column label="实际容量" align="center" prop="actual" />
        <el-table-column label="计划容量" align="center" prop="plan" />
        <el-table-column label="开工时间" align="center" prop="onStreamTime" width="120" />
        <el-table-column label="打卡范围" align="center" prop="punchRange" />
        <el-table-column label="设计总量" align="center" prop="designTotal" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="260">
          <template #default="scope">
            <el-space>
              <el-button link type="primary" icon="FolderOpened" @click="handleShowUpload(scope.row)">导入安全协议书 </el-button>
              <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['project:project:edit']">修改 </el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['project:project:remove']">删除 </el-button>
            </el-space>
          </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="projectFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入项目简称" />
        </el-form-item>
        <el-form-item label="项目地址" prop="projectSite">
          <el-input v-model="form.projectSite" placeholder="请输入项目地址" />
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input v-model="form.principal" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="principalPhone">
          <el-input v-model="form.principalPhone" placeholder="请输入负责人电话" />
        </el-form-item>
        <el-form-item label="实际容量" prop="actual">
          <el-input v-model="form.actual" placeholder="请输入实际容量" />
        </el-form-item>
        <el-form-item label="计划容量" prop="plan">
          <el-input v-model="form.plan" placeholder="请输入计划容量" />
        </el-form-item>
        <el-form-item label="开工时间" prop="onStreamTime">
          <el-date-picker clearable v-model="form.onStreamTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开工时间" />
        </el-form-item>
        <el-form-item label="打卡范围" prop="punchRange">
          <el-input v-model="form.punchRange" placeholder="请输入打卡范围" />
        </el-form-item>
        <el-form-item label="设计总量" prop="designTotal">
          <el-input v-model="form.designTotal" placeholder="请输入设计总量" />
        </el-form-item>
        <el-form-item label="安全协议书" prop="securityAgreement">
          <file-upload v-model="form.securityAgreement" :limit="1" :file-type="['pdf']" :file-size="50" />
        </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 v-model="uploadVisible" title="上传安全协议书" width="400">
      <file-upload v-model="fileUploadParam.securityAgreement" :limit="1" :file-type="['pdf']" :file-size="50" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-loading="buttonLoading" type="primary" @click="updateProjectFile"> 提交</el-button>
          <el-button @click="uploadVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project" lang="ts">
import { addProject, delProject, getProject, listProject, updateProject } from '@/api/project/project';
import { ProjectForm, ProjectQuery, ProjectVO } from '@/api/project/project/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, project_category_type } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'project_category_type'));

const projectList = ref<ProjectVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const projectFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProjectForm = {
  id: undefined,
  projectName: undefined,
  shortName: undefined,
  pId: undefined,
  status: undefined,
  picUrl: undefined,
  remark: undefined,
  type: undefined,
  isType: undefined,
  deletedAt: undefined,
  projectSite: undefined,
  principal: undefined,
  principalPhone: undefined,
  actual: undefined,
  plan: undefined,
  onStreamTime: undefined,
  punchRange: undefined,
  designTotal: undefined,
  securityAgreement: undefined,
  sort: undefined,
  showHidden: undefined,
  isDelete: undefined
};
const data = reactive<PageData<ProjectForm, ProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: undefined,
    shortName: undefined,
    pId: undefined,
    status: undefined,
    picUrl: undefined,
    type: undefined,
    isType: undefined,
    deletedAt: undefined,
    projectSite: undefined,
    principal: undefined,
    principalPhone: undefined,
    actual: undefined,
    plan: undefined,
    onStreamTime: undefined,
    punchRange: undefined,
    designTotal: undefined,
    securityAgreement: undefined,
    sort: undefined,
    showHidden: undefined,
    isDelete: undefined,
    params: {}
  },
  rules: {
    punchRange: [{ required: true, message: '打卡范围不能为空', trigger: 'blur' }],
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    shortName: [{ required: true, message: '项目简称不能为空', trigger: 'blur' }],
    projectSite: [{ required: true, message: '项目地址不能为空', trigger: 'blur' }]
  }
});

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

/** 查询项目列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProject(queryParams.value);
  projectList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  projectFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProjectVO[]) => {
  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?: ProjectVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getProject(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改项目';
};

/** 上传安全协议书按钮操作 */
const uploadVisible = ref<boolean>(false);
const fileUploadParam = ref({
  id: undefined,
  securityAgreement: undefined
});
const handleShowUpload = (row?: ProjectVO) => {
  fileUploadParam.value.securityAgreement = row.securityAgreement;
  fileUploadParam.value.id = row.id;
  uploadVisible.value = true;
};

const updateProjectFile = async () => {
  buttonLoading.value = true;
  await updateProject(fileUploadParam.value);
  proxy?.$modal.msgSuccess('上传成功');
  buttonLoading.value = false;
  uploadVisible.value = false;
  await getList();
};

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

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

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

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