<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      @submit.prevent
    >
      <el-form-item
        :label="t('admin.form.name', { type: t('admin.common.expert') })"
        prop="title"
      >
        <el-input
          v-model="queryParams.title"
          clearable
          :placeholder="
            t('admin.form.placeholder', {
              type: t('admin.form.name', {
                type: t('admin.common.expert'),
              }),
            })
          "
          size="small"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          icon="Search"
          size="small"
          type="primary"
          @click="handleQuery"
          ><!--搜索-->
          {{ t("common.search") }}
        </el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >{{ t("admin.common.reset") }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="plus"
          size="small"
          type="primary"
          @click="handleAddBind"
          >{{ t("admin.table.relatedExperts") }}
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!--  关联未被关联的专家  -->
    <el-dialog
      v-model="showExpertDialog"
      :title="t('admin.table.relatedExperts')"
    >
      <el-form
        ref="notBindExpertQueryRef"
        :inline="true"
        :model="notBindExpertQueryParams"
        @submit.prevent
      >
        <el-form-item
          :label="t('admin.form.name', { type: t('admin.common.expert') })"
          prop="name"
        >
          <el-input
            v-model="notBindExpertQueryParams.name"
            clearable
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.name', {
                  type: t('admin.common.expert'),
                }),
              })
            "
            size="small"
            style="width: 240px"
            @keyup.enter="getNotBindExpertList"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            icon="Search"
            size="small"
            type="primary"
            @click="getNotBindExpertList"
            ><!--搜索-->
            {{ t("common.search") }}
          </el-button>
          <el-button
            icon="Refresh"
            size="small"
            @click="resetNotBindExpertQuery"
            >{{ t("admin.common.reset") }}
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="notBindExpertList">
        <el-table-column :label="t('admin.common.dataNumber')" prop="id" />
        <el-table-column
          :show-overflow-tooltip="true"
          :label="t('admin.form.name', { type: t('admin.common.expert') })"
          prop="name"
        />
        <el-table-column :label="t('webContact.phone')" prop="mobile" />
        <el-table-column
          :label="t('admin.table.researchIndustry')"
          prop="industryStr"
        />
        <!--      <el-table-column label="申请（专利权）人" prop="applyName"/>-->
        <el-table-column
          align="center"
          :label="t('admin.table.enterTime')"
          prop="workTime"
        >
          <template #default="{ row }">
            <span>{{ dayjs(row.workTime).format("YYYY-MM-DD") }}</span>
          </template>
        </el-table-column>
        <!--        操作-->
        <el-table-column align="center" :label="t('admin.common.operation')">
          <template #default="{ row }">
            <el-button
              icon="plus"
              size="small"
              type="text"
              @click="submitBind(row.id)"
              ><!--关联-->{{ t("admin.table.relation") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="notBindExpertTotal > 0"
        v-model:limit="notBindExpertQueryParams.pageSize"
        v-model:page="notBindExpertQueryParams.pageNum"
        :total="notBindExpertTotal"
        @pagination="getNotBindExpertList"
      />
    </el-dialog>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column :label="t('admin.common.dataNumber')" prop="id" />
      <el-table-column
        :show-overflow-tooltip="true"
        :label="t('admin.form.name', { type: t('admin.common.expert') })"
        prop="name"
      />
      <el-table-column :label="t('webContact.phone')" prop="mobile" />
      <el-table-column
        :label="t('admin.table.researchIndustry')"
        prop="industryStr"
      />
      <!--      <el-table-column label="申请（专利权）人" prop="applyName"/>-->
      <el-table-column
        align="center"
        :label="t('admin.table.enterTime')"
        prop="workTime"
      >
        <template #default="{ row }">
          <span>{{ dayjs(row.workTime).format("YYYY-MM-DD") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        :label="t('admin.common.operation')"
      >
        <template #default="{ row }">
          <!--          <el-button-->
          <!--              icon="edit"-->
          <!--              size="small"-->
          <!--              type="text"-->
          <!--              @click="handleDeleteBind(row.id)"-->
          <!--          >编辑-->
          <!--          </el-button-->
          <!--          >-->
          <el-button
            icon="Delete"
            size="small"
            type="text"
            @click="handleDeleteBind(row.id)"
            ><!--取消关联-->
            {{ t("admin.table.cancelRelation") }}
          </el-button>
        </template>
      </el-table-column>
      <template #footer>
        <div class="dialog-footer">
          <!--          <el-button type="primary" @click="submitForm">{{ t("common.confirm") }}</el-button>-->
          <el-button>{{ t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />
    <!-- 添加或修改数据配置对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="800px">
      <el-form ref="expertRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="t('admin.form.expertName')" prop="title">
          <el-input
            v-model="form.title"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.form.expertName') })
            "
          />
        </el-form-item>
        <el-form-item :label="t('input.gender')" prop="gender">
          <el-input
            v-model="form.gender"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('input.gender'),
              })
            "
          />
        </el-form-item>
        <el-form-item :label="t('webContact.unit')" prop="unit">
          <el-input
            v-model="form.unit"
            :placeholder="
              t('admin.form.placeholder', { type: t('webContact.unit') })
            "
          />
        </el-form-item>
        <el-form-item
          :label="t('admin.form.researchDirection')"
          prop="researchDirection"
        >
          <InputBoxAdd
            ref="researchDirectionFormRef"
            v-model="form"
            :labelWidth="100"
            fieldKey="researchs"
            :placeholder="t('admin.form.researchDirection')"
            :title="t('admin.form.researchDirection')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >{{ t("common.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { reactive, ref, toRefs } from "vue";
import InputBoxAdd from "@/views/components/InputBoxAdd/index.vue";
import {
  bindExpert,
  deleteBindExpert,
  expertList,
  selectNotBindLaboratory,
} from "@/api/admin/laboratory/expert";
import Pagination from "@/components/Pagination/index.vue";
import { useI18n } from "vue-i18n";
import dayjs from "dayjs";
import modal from "@/plugins/modal";

const router = useRouter();
const { t } = useI18n();
const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const expertRef = ref();
const researchDirectionFormRef = ref();

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inventor: undefined,
  },
  form: {},
  rules: {},
});

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

const queryRef = ref();

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  expertList(queryParams.value)
    .then((resp) => {
      dataList.value = resp.rows;
      total.value = resp.total;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

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

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields();
  handleQuery();
}

/** 删除按钮操作 */
function handleDeleteBind(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        action: t("admin.table.cancelRelation"),
        type: t("admin.common.expert"),
        number: id,
      })
    )
    .then(function () {
      return deleteBindExpert(id);
    })
    .then(() => {
      getList();
      ElMessage.success(
        t("admin.common.success", {
          action: t("admin.table.cancelRelation"),
        })
      );
    })
    .catch((err) => {
      console.log(err);
    });
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    title: undefined,
    ext: undefined,
    author: undefined,
    publish_at: undefined,
    keywords: [],
    remark: undefined,
  };
  expertRef.value?.resetFields();
}

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

// 是否显示关联专家dialog
const showExpertDialog = ref(false);
// 未绑定专家列表
const notBindExpertList = ref([]);
// 未绑定专家总数
const notBindExpertTotal = ref(0);
const notBindExpertQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
});

const notBindExpertQueryRef = ref();

const getNotBindExpertList = () => {
  selectNotBindLaboratory(notBindExpertQueryParams).then((resp) => {
    notBindExpertList.value = resp.rows;
    notBindExpertTotal.value = resp.total;
  });
};

const handleAddBind = () => {
  getNotBindExpertList();
  showExpertDialog.value = true;
};

/**
 * 重置未绑定专家查询条件
 */
const resetNotBindExpertQuery = () => {
  notBindExpertQueryParams.pageNum = 1;
  notBindExpertQueryParams.pageSize = 10;
  notBindExpertQueryParams.name = undefined;
  notBindExpertQueryRef.value.resetFields();
  getNotBindExpertList();
};

/**
 * 关联专家
 * @param id
 */
const submitBind = (id) => {
  modal
    .confirm(
      /*"是否确认关联该专家?"*/
      t("admin.common.confirmAction", {
        action: t("admin.table.relation"),
        type: t("admin.common.expert"),
        number: id,
      })
    )
    .then(function () {
      return bindExpert(id);
    })
    .then(() => {
      getNotBindExpertList();
      ElMessage.success(
        /*"关联成功"*/
        t("admin.common.success", {
          action: t("admin.table.relation"),
        })
      );
    })
    .catch((err) => {
      console.log(err);
    });
};

const handleUpdate = () => {
  reset();
  title.value = t("admin.form.edit", {
    type: t("admin.common.expert"),
  });
  open.value = true;
};

/** 提交按钮 */
function submitForm() {
  expertRef.value?.validate((valid) => {
    const keywordsFormValid = researchDirectionFormRef?.value.validateForm();
    if (valid && keywordsFormValid) {
      if (form.value.id) {
        // TODO
        paperEdit(form.value).then((response) => {
          ElMessage.success(t("admin.common.editSuccess"));
          open.value = false;
          getList();
        });
      } else {
        paperAdd(form.value).then((response) => {
          ElMessage.success(t("admin.common.addSuccess"));
          open.value = false;
          getList();
        });
      }
    }
  });
}

getList();
</script>
