<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      @submit.prevent
    >
      <el-form-item
        :label="
          t('admin.form.name', {
            type: t('admin.common.researchProject'),
          })
        "
        prop="title"
      >
        <el-input
          v-model="queryParams.title"
          :placeholder="
            t('admin.form.placeholder', {
              type: t('admin.form.name', {
                type: t('admin.common.researchProject'),
              }),
            })
          "
          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"
        >
          {{ t("admin.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
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
        >
          {{ t("admin.common.add") }}
        </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="t('admin.common.dataNumber')" prop="id" />
      <el-table-column
        :label="
          t('admin.form.name', {
            type: t('admin.common.researchProject'),
          })
        "
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column :label="t('admin.common.type')" prop="kind" />
      <el-table-column :label="t('admin.table.topicRole')" prop="role">
        <template #default="scope">
          <div v-if="scope.row.role == 1">
            <!--承担单位-->
            {{ t("admin.form.undertakeUnit") }}
          </div>
          <div v-else-if="scope.row.role == 2">
            <!--参与单位-->
            {{ t("admin.form.participatingUnit") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="t('admin.form.topicLeader')" prop="director" />
      <el-table-column
        :label="t('admin.table.publishDate')"
        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="t('admin.common.operation')"
        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-->
          <!--                ? t("admin.table.putOff")-->
          <!--                : t("admin.table.putOn")-->
          <!--            }}-->
          <!--          </el-button>-->
          <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="showEditDialog"
      width="820px"
      append-to-body
    >
      <el-form
        ref="researchRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item
          :label="
            t('admin.form.name', {
              type: t('admin.common.researchProject'),
            })
          "
          prop="title"
        >
          <el-input
            v-model="form.title"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.name', {
                  type: t('admin.common.researchProject'),
                }),
              })
            "
          />
        </el-form-item>
        <el-form-item :label="t('admin.table.topicRole')" prop="role">
          <el-radio v-model="form.role" label="1"
            ><!--承担单位-->
            {{ t("admin.form.undertakeUnit") }}
          </el-radio>
          <el-radio v-model="form.role" label="2"
            ><!--参与单位-->
            {{ t("admin.form.participatingUnit") }}
          </el-radio>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.funding')" 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="
                  t('admin.form.placeholder', {
                    type: t('admin.form.funding'),
                  })
                "
              >
                <template #append
                  >{{ t("admin.table.tenThousandYuan") }}
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.fundingSource')" prop="source">
              <el-input
                v-model="form.source"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.fundingSource'),
                  })
                "
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="t('admin.table.startDate')" prop="beginTime">
              <el-date-picker
                v-model="form.beginTime"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.table.startDate'),
                  })
                "
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('admin.table.endDate')" prop="finishTime">
              <el-date-picker
                v-model="form.finishTime"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="
                  t('admin.form.pleaseSelect', {
                    type: t('admin.table.startDate'),
                  })
                "
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.projectType')" prop="kind">
              <el-input
                v-model="form.kind"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.projectType'),
                  })
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.topicLeader')" prop="director">
              <el-input
                v-model="form.director"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.topicLeader'),
                  })
                "
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- //TODO:添加项目简介字段 -->
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="t('admin.form.projectIntroduction')"
              prop="introduce"
            >
              <!--              <WangEditor-->
              <!--                v-model="form.introduce"-->
              <!--                width="100%"-->
              <!--                min-height="150px"-->
              <!--                @blur="researchRef.validateField(`introduce`)"-->
              <!--              ></WangEditor>-->
              <el-input
                type="textarea"
                v-model="form.introduce"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.projectIntroduction'),
                  })
                "
                :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"
            >{{ t("admin.common.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ t("admin.common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  deleteTechnologyProjectByIds,
  insertTechnologyProject,
  technologyProjectList,
  updateTechnologyProject,
} from "@/api/admin/expert/research";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import { cloneDeep } from "lodash-es";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { computed, reactive, ref, toRefs } from "vue";

const { t } = useI18n();
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: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.name", {
              type: t("admin.common.researchProject"),
            }),
          })
        ),
        trigger: "blur",
      },
    ],
    amount: [
      {
        required: true,
        /*"资助经费不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.funding"),
          })
        ),
        trigger: "blur",
      },
    ],
    source: [
      {
        required: true,
        /*"资助来源不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.fundingSource"),
          })
        ),
        trigger: "blur",
      },
    ],
    beginTime: [
      {
        required: true,
        message: computed(() =>
          t("admin.form.pleaseSelect", {
            type: t("admin.table.startDate"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
    finishTime: [
      {
        required: true,
        message: computed(() =>
          t("admin.form.pleaseSelect", {
            type: t("admin.table.endDate"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
    kind: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", { type: t("admin.form.projectType") })
        ),
        trigger: "blur",
      },
    ],
    director: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.topicLeader"),
          })
        ),
        trigger: "blur",
      },
    ],
    introduce: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.projectIntroduction"),
          })
        ),
        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 ? t("admin.table.putOn") : t("admin.table.putOff");
  modal
    // .confirm(`确认要${text}"${row.id}"的数据吗?`)
    .confirm(
      t("admin.common.confirmAction", {
        type: t("admin.common.researchProject"),
        action: text,
        number: row.id,
      })
    )
    .then(() => {
      const shelfStatus = row.shelfStatus == 1 ? 2 : 1;
      return updateTechnologyProject({ id: row.id, shelfStatus });
    })
    .then(() => {
      getList();
      ElMessage.success(
        t("admin.common.success", {
          action: text,
        })
      );
    })
    .catch((err) => {
      console.log(err);
    });
}

/** 删除按钮操作 */
function handleDelete(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        type: t("admin.common.researchProject"),
        action: t("admin.common.delete"),
        number: id,
      })
    )
    .then(async () => {
      await deleteTechnologyProjectByIds({ ids: [id] });
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    });
}

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

/** 修改数据 */
function handleUpdate(row) {
  reset();
  form.value = cloneDeep(row);
  showEditDialog.value = true;
  title.value = t("admin.form.editData");
}

/** 提交按钮 */
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(t("admin.common.editSuccess"));
        showEditDialog.value = false;
        getList();
      } else {
        await insertTechnologyProject(form.value);
        ElMessage.success(t("admin.common.addSuccess"));
        showEditDialog.value = false;
        getList();
      }
    }
  });
}

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

getList();
</script>
