<template>
  <div class="app-container">
    <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>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="数据编号" prop="id" width="150" />
      <el-table-column
        label="合作企业名称"
        align="center"
        prop="name"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column label="关联论文" align="center" prop="paper_title">
        <template #default="scope">
          <div v-for="(item, index) in scope.row.paper_title" :key="index">
            <div class="ellipsis" v-if="index <= 2">{{ item }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="关联专利" align="center" prop="patent_title">
        <template #default="scope">
          <div v-for="(item, index) in scope.row.patent_title" :key="index">
            <div class="ellipsis text-left" v-if="index <= 2">{{ item }}</div>
          </div>
        </template>
      </el-table-column>
      <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="scope">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</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="open"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="企业名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="关联论文:" prop="papers">
          <el-select
            ref="selectDom"
            style="width: 100%"
            v-model="form.papers"
            value-key="id"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="paperMethod"
            :loading="paperSelectLoading"
            placeholder="请选择关联论文"
          >
            <el-option
              style="max-width: 360px"
              v-for="item in paperOptions"
              :key="item.id"
              :label="item.title"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联专利:" prop="patents">
          <el-select
            style="width: 100%"
            v-model="form.patents"
            value-key="id"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="patentMethod"
            :loading="patentSelectLoading"
            placeholder="请选择关联专利"
          >
            <el-option
              style="max-width: 360px"
              v-for="item in patentOptions"
              :key="item.id"
              :label="item.title"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </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 name="Already">
// import {
//   enterprise,
//   enterpriseAdd,
//   enterpriseDelete,
//   enterpriseEdit,
// } from "@/api/admin/expert/demand";
// 专利，论文
// import { patentSelect, paperSelect } from "@/api/admin/expert/technology";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
// const router = useRouter();
// const { proxy } = getCurrentInstance();

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
// const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    page_num: 1,
    page_size: 10,
    mode: 1,
  },
  rules: {
    name: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],
    papers: [
      {
        type: "array",
        required: true,
        message: "关联论文不能为空",
        trigger: ["blur", "change"],
      },
    ],
    patents: [
      {
        type: "array",
        required: true,
        message: "关联专利不能为空",
        trigger: ["blur", "change"],
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);
// 论文
const paperOptions = ref([]);
const paperSelectLoading = ref(false);
const formRef = ref();
const paperMethod = (title) => {
  if (title) {
    paperSelectLoading.value = true;
    paperSelect({ title }).then((res) => {
      paperSelectLoading.value = false;
      paperOptions.value = res.data;
    });
  } else {
    paperOptions.value = [];
  }
};
// 专利
const patentOptions = ref([]);
const patentSelectLoading = ref(false);
const patentMethod = (title) => {
  if (title) {
    patentSelectLoading.value = true;
    patentSelect({ title }).then((res) => {
      patentSelectLoading.value = false;
      patentOptions.value = res.data;
    });
  } else {
    patentOptions.value = [];
  }
};

/** 查询数据列表 */
function getList() {
  loading.value = true;
  //   enterprise(queryParams.value).then((response) => {
  //     response.data.data.map((item) => {
  //       item.paper_title = item.paper_title.split("&&");
  //       item.patent_title = item.patent_title.split("&&");
  //     });
  //     dataList.value = response.data.data;
  //     total.value = response.data.count;
  //     loading.value = false;
  //   });
  loading.value = false;
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
// function resetQuery() {
//     // if()
// //   proxy.resetForm("queryRef");
//   handleQuery();
// }
/** 删除按钮操作 */
function handleDelete(id) {
  ElMessageBox.confirm('是否确认删除数据编号为"' + id + '"的数据项?')
    .then(function () {
      return enterpriseDelete({ id: id });
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    name: undefined,
    mode: 1,
    papers: [],
    patents: [],
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
}
/** 添加数据 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加数据";
}
/** 修改数据 */
function handleUpdate(row) {
  // reset();
  let formData = Object.assign({}, row);
  let papers = [];
  let patents = [];
  formData.papers.map((item, index) => {
    papers.push({
      id: item,
      title: formData.paper_title[index],
    });
  });
  formData.patents.map((item, index) => {
    patents.push({
      id: item,
      title: formData.patent_title[index],
    });
  });
  paperOptions.value = formData.papers = papers;
  patentOptions.value = formData.patents = patents;
  form.value = formData;
  open.value = true;
  title.value = "修改数据";

  nextTick(() => {
    // console.log(proxy.$refs["selectDom"]); // .cachedOptions
  });
}
/** 提交按钮 */
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      let formData = Object.assign({}, form.value);
      let papers = [];
      let patents = [];
      formData.papers.map((item) => {
        papers.push(item.id);
      });
      formData.patents.map((item) => {
        patents.push(item.id);
      });
      formData.papers = papers;
      formData.patents = patents;
      if (form.value.id != undefined) {
        enterpriseEdit(formData).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        enterpriseAdd(formData).then((response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>
