<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"
        >
          {{ t("admin.common.add") }}
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column
        :label="t('admin.common.dataNumber')"
        prop="id"
        width="150"
      />
      <el-table-column
        :label="
          t('admin.form.name', { type: t('admin.form.cooperationCompany') })
        "
        align="center"
        prop="name"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column
        :label="t('admin.table.relatedPaper')"
        align="center"
        prop="paperStr"
        show-overflow-tooltip
      >
        <!-- <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="t('admin.table.relatedPatent')"
        align="center"
        prop="patentStr"
        show-overflow-tooltip
      >
        <!-- <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="t('admin.table.createTime')"
        align="center"
        prop="created_at"
      >
        <template #default="{ row }">
          <span>{{ dayjs(row.created_at).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('admin.common.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(row)"
            >{{ t("admin.common.edit") }}
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(row.id)"
          >
            {{ t("admin.common.delete") }}
          </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="t('admin.form.name', { type: t('admin.common.company') })"
          prop="name"
        >
          <el-input
            v-model="form.name"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.common.company') })
            "
          />
        </el-form-item>
        <el-form-item :label="t('admin.table.relatedPaper')" 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="
              t('admin.form.pleaseSelect', {
                type: t('admin.table.relatedPaper'),
              })
            "
          >
            <el-option
              style="max-width: 360px"
              v-for="item in paperOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('admin.table.relatedPatent')" prop="patents">
          <el-select
            @change="changePattent"
            style="width: 100%"
            v-model="form.patents"
            multiple
            value-key="id"
            filterable
            remote
            reserve-keyword
            :remote-method="patentMethod"
            :loading="patentSelectLoading"
            :placeholder="
              t('admin.form.pleaseSelect', {
                type: t('admin.table.relatedPatent'),
              })
            "
          >
            <el-option
              style="max-width: 360px"
              v-for="item in patentOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >{{ t("admin.common.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ t("admin.common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Already">
import {
  deleteExpertCooperateEnterpriseByIds,
  getExpertCooperateEnterpriseList,
  insertExpertCooperateEnterprise,
  updateExpertCooperateEnterprise,
} from "@/api/admin/expert/demand";
import { search } from "@/api/website/home";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import { paperList } from "@/api/admin/expert/technology";
import { useI18n } from "vue-i18n";
import { computed, nextTick, reactive, ref, toRefs } from "vue";

const { t } = useI18n();

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

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mode: 1,
  },
  rules: {
    name: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", { type: t("admin.common.company") })
        ),
        trigger: "blur",
      },
    ],
    papers: [
      {
        type: "array",
        required: true,
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.table.relatedPaper"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
    patents: [
      {
        type: "array",
        required: true,
        /*"关联专利不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.table.relatedPatent"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);
// 论文
const paperOptions = ref([]);
// const paperStr = ref("");
const paperSelectLoading = ref(false);
const formRef = ref();
const paperMethod = (title) => {
  if (title) {
    paperSelectLoading.value = true;
    paperList({ title, pageNum: 1, pageSize: 10 }).then((res) => {
      paperSelectLoading.value = false;
      paperOptions.value = res.rows;
    });
  } else {
    paperOptions.value = [];
  }
};
// 专利
const patentOptions = ref([]);
const patentSelectLoading = ref(false);
const patentMethod = (title) => {
  if (title) {
    patentSelectLoading.value = true;
    search({
      searchType: 4,
      queryType: 1,
      query: title,
      pageNum: 1,
      pageSize: 10,
    }).then((res) => {
      patentSelectLoading.value = false;
      patentOptions.value = res.list;
    });
  } else {
    patentOptions.value = [];
  }
};

/** 查询数据列表 */
async function getList() {
  loading.value = true;
  try {
    const resp = await getExpertCooperateEnterpriseList(queryParams.value);
    dataList.value = resp.rows;
    total.value = resp.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
}

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

const changePattent = (val) => {
  console.log(12313);
  console.log(val);
};
/** 重置按钮操作 */
// function resetQuery() {
//     // if()
// //   proxy.resetForm("queryRef");
//   handleQuery();
// }
/** 删除按钮操作 */
function handleDelete(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        type: t("admin.common.item"),
        number: id,
        action: t("admin.common.delete"),
      })
    )
    .then(function () {
      return deleteExpertCooperateEnterpriseByIds(id);
    })
    .then(() => {
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    })
    .catch(() => {});
}

/** 重置新增的表单以及其他数据  */
const 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 = t("admin.form.addData");
}

/** 修改数据 */
function handleUpdate(row) {
  // reset();
  let formData = Object.assign({}, row);
  let papers = [];
  let patents = [];
  formData.papers = row.paper ? row.paper.split(",") : [];
  formData.patents = row.patent ? row.patent.split(",") : [];

  //TODO: // formData.papers.map((item, index) => {
  //TODO: //   papers.push({
  //TODO: //     id: item,
  //TODO: //     title: formData.paper_title[index],
  //TODO: //   });
  //TODO: // });
  //TODO: // formData.patents.map((item, index) => {
  //TODO: //   patents.push({
  //TODO: //     id: item,
  //TODO: //     title: formData.patent_title[index],
  //TODO: //   });
  //TODO: // });
  const paperStrs = row.paperStr ? row.paperStr.split(",") : [];
  formData.papers.forEach((el, index) => {
    papers.push({
      id: el,
      title: paperStrs[index],
    });
  });

  const patentStrs = row.patentStr ? row.patentStr.split(",") : [];
  formData.patents.forEach((el, index) => {
    patents.push({
      id: el,
      title: patentStrs[index],
    });
  });

  paperOptions.value = papers;
  patentOptions.value = patents;
  form.value = formData;
  open.value = true;
  title.value = t("admin.form.editData");

  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;
      form.value.patent = form.value.patents.join(",");
      form.value.paper = form.value.papers.join(",");
      if (form.value.id != undefined) {
        updateExpertCooperateEnterprise(form.value).then((response) => {
          ElMessage.success(t("admin.common.editSuccess"));
          open.value = false;
          getList();
        });
      } else {
        insertExpertCooperateEnterprise(form.value).then((response) => {
          ElMessage.success(t("admin.common.addSuccess"));
          open.value = false;
          getList();
        });
      }
    }
  });
}

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

getList();
</script>
