<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      @submit.prevent
    >
      <el-form-item label="科研项目名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入科研项目名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="数据编号" prop="id" />
      <el-table-column
        label="科研项目名称"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="类型" prop="kind" />
      <el-table-column label="课题角色" prop="role">
        <template #default="scope">
          <div v-if="scope.row.role == 1">承担单位</div>
          <div v-else-if="scope.row.role == 2">参与单位</div>
        </template>
      </el-table-column>
      <el-table-column label="课题负责人" prop="director" />
      <el-table-column label="发布日期" align="center" prop="created_at">
        <template #default="scope">
          <span>{{
            dayjs(scope.row.created_at).format("YYYY-MM-DD HH:mm:ss")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="Download"
            @click="handleShelf(row)"
            >{{ row.shelfStatus == 1 ? "下架" : "上架" }}</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(row.id)"
            >删除</el-button
          >
        </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-dialog
      :title="title"
      v-model="showEditDialog"
      width="720px"
      append-to-body
    >
      <el-form
        ref="researchRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="科研项目名称:" prop="title">
          <el-input v-model="form.title" placeholder="请输入科研项目名称" />
        </el-form-item>
        <el-form-item label="课题角色:" prop="role">
          <el-radio v-model="form.role" label="1">承担单位</el-radio>
          <el-radio v-model="form.role" label="2">参与单位</el-radio>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资助经费:" prop="amount">
              <el-input
                v-model="form.amount"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                placeholder="请输入资助经费"
              >
                <template #append>万元</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资助来源:" prop="source">
              <el-input v-model="form.source" placeholder="请输入资助来源" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期:" prop="beginTime">
              <el-date-picker
                v-model="form.beginTime"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期:" prop="finishTime">
              <el-date-picker
                v-model="form.finishTime"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目类型:" prop="kind">
              <el-input v-model="form.kind" placeholder="请输入项目类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课题负责人:" prop="director">
              <el-input
                v-model="form.director"
                placeholder="请输入课题负责人"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- //TODO:添加项目简介字段 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目简介:" prop="introduce">
              <WangEditor
                v-model="form.introduce"
                width="100%"
                min-height="150px"
                @blur="researchRef.validateField(`introduce`)"
              ></WangEditor>
              <!-- <el-input
                type="textarea"
                v-model="form.kind"
                placeholder="请输入项目简介"
                :autosize="{ minRows: 8, maxRows: 16 }"
              /> -->
            </el-form-item>
          </el-col>
        </el-row>
      </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>
  </div>
</template>

<script setup>
import {
  technologyProjectList,
  insertTechnologyProject,
  deleteTechnologyProjectByIds,
  updateTechnologyProject,
} from "@/api/admin/expert/research";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash-unified";
import { useRouter } from "vue-router";
const router = useRouter();

const dataList = ref([]);
const showEditDialog = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const researchRef = ref();
const queryRef = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    title: [
      { required: true, message: "科研项目名称不能为空", trigger: "blur" },
    ],
    amount: [{ required: true, message: "资助经费不能为空", trigger: "blur" }],
    source: [{ required: true, message: "资助来源不能为空", trigger: "blur" }],
    beginTime: [
      {
        required: true,
        message: "请选择开始日期",
        trigger: ["blur", "change"],
      },
    ],
    finishTime: [
      {
        required: true,
        message: "请选择结束日期",
        trigger: ["blur", "change"],
      },
    ],
    kind: [{ required: true, message: "项目类型不能为空", trigger: "blur" }],
    director: [
      { required: true, message: "课题负责人不能为空", trigger: "blur" },
    ],
    introduce: [
      { required: true, message: "项目简介不能为空", trigger: "blur" },
    ],
  },
});

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

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  const resp = await technologyProjectList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  // proxy.resetForm("queryRef");
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  handleQuery();
}
function handleShelf(row) {
  const text = row.shelfStatus == 2 ? "上架" : "下架";
  ElMessageBox.confirm(`确认要${text}"${row.id}"的数据吗?`)
    .then(() => {
      const shelfStatus = row.shelfStatus == 1 ? 2 : 1;
      return updateTechnologyProject({ id: row.id, shelfStatus });
    })
    .then(() => {
      getList();
      ElMessage.success(text + "成功");
    })
    .catch((err) => {
      console.log(err);
    });
}
/** 删除按钮操作 */
function handleDelete(id) {
  ElMessageBox.confirm(`是否确认删除数据编号为"${id}"的数据项?`).then(
    async () => {
      await deleteTechnologyProjectByIds({ ids: [id] });
      getList();
      ElMessage.success("删除成功");
    }
  );
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    // id: undefined,
    // title: undefined,
    // role: 1,
    // amount: undefined,
    // source: undefined,
    // beginTime: undefined,
    // finishTime: undefined,
    // kind: undefined,
    // director: undefined,
  };
  if (researchRef.value) {
    researchRef.value.resetFields();
  }
}
/** 添加数据 */
function handleAdd() {
  reset();
  showEditDialog.value = true;
  title.value = "添加数据";
}
/** 修改数据 */
function handleUpdate(row) {
  reset();
  form.value = cloneDeep(row);
  showEditDialog.value = true;
  title.value = "修改数据";
}
/** 提交按钮 */
function submitForm() {
  researchRef.value.validate(async (valid) => {
    if (valid) {
      form.value.amount = form.value.amount - 0;
      if (form.value.id) {
        await updateTechnologyProject(form.value);
        ElMessage.success("修改成功");
        showEditDialog.value = false;
        getList();
      } else {
        await insertTechnologyProject(form.value);
        ElMessage.success("新增成功");
        showEditDialog.value = false;
        getList();
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  showEditDialog.value = false;
  reset();
}

getList();
</script>
