<template>
  <div class="q-pa-md">
    <q-table
      ref="tableRef"
      title="项目信息"
      :style="{ height: tableHeight + 'px' }"
      :rows="rows"
      :columns="columnDefs"
      row-key="id"
      v-model:pagination="pagination"
      :rows-per-page-options="[10, 20, 50, 100]"
      :loading="loading"
      :filter="filter"
      binary-state-sort
      @request="onRequest"
    >
      <template v-slot:top-right>
        <q-input
          dense
          debounce="1000"
          v-model="filter.name"
          label="名称"
        ></q-input>
        <q-btn flat round color="primary" icon="search" />
        <q-btn color="primary" label="新建" @click="createFormShow = true" />
      </template>

      <template v-slot:body-cell-operations="props">
        <q-td :props="props">
          <div class="q-gutter-sm row justify-center">
            <q-btn
              color="primary"
              :disable="operateDisabled"
              label="编辑"
              @click="editData(props.row)"
            />
            <q-btn
              color="primary"
              :disable="operateDisabled"
              label="关联"
              @click="editLinkData(props.row)"
            />
            <q-btn
              color="red"
              :disable="operateDisabled"
              label="删除"
              @click="deleteData(props.row)"
            />
          </div>
        </q-td>
      </template>
    </q-table>

    <q-dialog
      v-model="createFormShow"
      persistent
      transition-show="scale"
      transition-hide="scale"
    >
      <q-card style="width: 300px">
        <q-card-section>
          <q-form
            ref="myForm"
            @submit="onCreate"
            @reset="onReset"
            class="q-gutter-md"
          >
            <div class="text-h6">
              {{ editInfo.id ? '编辑项目信息' : '新建项目信息' }}
            </div>
            <q-input
              outlined
              label="名称"
              v-model="editInfo.name"
              lazy-rules
              :rules="[(val) => val.length > 0 || '请输入名称！']"
            />
            <q-input
              outlined
              label="编码"
              v-model="editInfo.code"
              lazy-rules
              :rules="[(val) => val.length > 0 || '请输入编码！']"
            />

            <q-card-actions align="right">
              <q-btn color="primary" label="保存" type="submit" />
              <q-btn label="取消" type="reset" v-close-popup />
            </q-card-actions>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
    <q-dialog
      v-model="linkFormShow"
      persistent
      transition-show="scale"
      transition-hide="scale"
    >
      <q-card style="width: 300px">
        <q-card-section>
          <q-form
            ref="linkForm"
            @submit="onLinkSave"
            @reset="onLinkReset"
            class="q-gutter-md"
          >
            <div class="text-h6">编辑项目关联信息</div>
            <q-input
              outlined
              label="名称"
              v-model="editLinkInfo.name"
              disable
            />
            <q-select
              outlined
              class="q-mt-md"
              use-chips
              v-model="editLinkInfo.mids"
              :options="midsOptions"
              multiple
              map-options
              emit-value
              label="发布图"
              lazy-rules
              :rules="[(val) => val.length > 0 || '发布图不能为空！']"
            ></q-select>
            <q-select
              outlined
              class="q-mt-md"
              use-chips
              v-model="editLinkInfo.sids"
              :options="sidsOptions"
              multiple
              map-options
              emit-value
              label="列车尺寸"
              lazy-rules
              :rules="[(val) => val.length > 0 || '列车尺寸不能为空！']"
            ></q-select>

            <q-card-actions align="right">
              <q-btn color="primary" label="保存" type="submit" />
              <q-btn label="取消" type="reset" v-close-popup />
            </q-card-actions>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useQuasar, type QTableColumn, QForm } from 'quasar';
import {
  pageQuery,
  createProject,
  deleteProject,
  saveProjectData,
  createParams,
  ProjectItem,
  getProjectInfo,
} from '../api/ProjectApi';
import {
  saveProjectLink,
  getProjectLinkInfo,
  SaveLinkParams,
} from '../api/ProjectLinkApi';
import { ApiError } from 'src/boot/axios';
import { getPublishList } from 'src/api/PublishApi';
import { getAllTrainSizeList } from 'src/api/TrainModelApi';

interface OptionsItem {
  label: string;
  value: number;
}

const $q = useQuasar();

const props = withDefaults(
  defineProps<{
    sizeHeight: number;
  }>(),
  { sizeHeight: 500 }
);

const tableHeight = computed(() => {
  return props.sizeHeight - 32;
});

onMounted(() => {
  getAllPublish();
  getAllTrainSize();
  tableRef.value.requestServerInteraction();
});

const columnDefs: QTableColumn[] = [
  {
    name: 'name',
    label: '名称',
    field: 'name',
    required: true,
    align: 'center',
  },
  {
    name: 'code',
    label: '编码',
    field: 'code',
    align: 'center',
  },
  {
    name: 'created_at',
    label: '创建时间',
    field: 'created_at',
    align: 'center',
  },
  {
    name: 'update_at',
    label: '更新时间',
    field: 'update_at',
    align: 'center',
  },
  { name: 'operations', label: '操作', field: 'operations', align: 'center' },
];

const operateDisabled = ref(false);
const tableRef = ref();
const rows = reactive([]);
const filter = reactive({
  name: '',
});
const loading = ref(false);
const pagination = ref({
  sortBy: 'desc',
  descending: false,
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 10,
});

// eslint-disable-next-line
async function onRequest(props: any) {
  const { page, rowsPerPage, sortBy, descending } = props.pagination;
  const filter = props.filter;

  loading.value = true;
  try {
    let response = await pageQuery({
      current: page,
      size: rowsPerPage,
      name: filter.name,
    });
    const pageData = response;
    pagination.value.rowsNumber = pageData.total;
    pagination.value.page = page;
    pagination.value.rowsPerPage = rowsPerPage;
    pagination.value.sortBy = sortBy;
    pagination.value.descending = descending;
    rows.splice(0, rows.length, ...(pageData.records as []));
  } catch (err) {
    const error = err as ApiError;
    $q.notify({
      type: 'negative',
      message: error.title,
    });
  } finally {
    loading.value = false;
  }
}

const createFormShow = ref(false);
const myForm = ref<QForm | null>(null);
function onCreate() {
  myForm.value?.validate().then(async (res) => {
    if (res) {
      operateDisabled.value = true;
      try {
        const params: createParams = {
          name: editInfo.name,
          code: editInfo.code,
        };
        if (editInfo.id) {
          await saveProjectData(+editInfo.id, params);
        } else {
          await createProject(params);
        }
        onReset();
        createFormShow.value = false;
        tableRef.value.requestServerInteraction(); // 刷新列表
      } catch (err) {
        const error = err as ApiError;
        $q.notify({
          type: 'negative',
          message: error.title,
        });
      } finally {
        operateDisabled.value = false;
      }
    }
  });
}

function onReset() {
  editInfo.id = '';
  editInfo.name = '';
  editInfo.code = '';
  myForm.value?.resetValidation();
}

async function deleteData(row: ProjectItem) {
  operateDisabled.value = true;
  $q.dialog({
    title: '确认',
    message: `确认删除项目 "${row.name}" 吗?`,
    cancel: true,
  })
    .onOk(async () => {
      try {
        await deleteProject(row.id);
        tableRef.value.requestServerInteraction(); // 刷新列表
      } catch (err) {
        const error = err as ApiError;
        $q.notify({
          type: 'negative',
          message: error.title,
        });
      }
    })
    .onDismiss(() => {
      operateDisabled.value = false;
    });
}

const editInfo = reactive({
  id: '',
  name: '',
  code: '',
});
function editData(row: ProjectItem) {
  getProjectInfo(row.id)
    .then((res: ProjectItem) => {
      editInfo.id = res.id + '';
      editInfo.name = res.name;
      editInfo.code = res.code;
      createFormShow.value = true;
    })
    .catch((err) => {
      const error = err as ApiError;
      $q.notify({
        type: 'negative',
        message: error.title,
      });
    });
}

interface LinkParams extends Pick<SaveLinkParams, 'mids' | 'sids'> {
  name: string;
  pid: string;
}

const editLinkInfo = reactive<LinkParams>({
  name: '',
  pid: '',
  mids: [],
  sids: [],
});
function editLinkData(row: ProjectItem) {
  onLinkReset();
  getProjectLinkInfo(row.id)
    .then((res) => {
      editLinkInfo.name = res.name;
      editLinkInfo.pid = res.pid + '';
      res.mapInfoLinks?.forEach((item) => {
        editLinkInfo.mids.push(item.id);
      });
      res.trainSizeLinks?.forEach((item) => {
        editLinkInfo.sids.push(item.id);
      });
    })
    .catch((err) => {
      const error = err as ApiError;
      $q.notify({
        type: 'negative',
        message: error.title,
      });
    });
  linkFormShow.value = true;
}
const linkFormShow = ref(false);
const linkForm = ref<QForm | null>(null);
function onLinkSave() {
  linkForm.value?.validate().then(async (res) => {
    if (res) {
      try {
        const params: SaveLinkParams = {
          pid: +editLinkInfo.pid,
          mids: editLinkInfo.mids,
          sids: editLinkInfo.sids,
        };
        await saveProjectLink(params);
        onLinkReset();
        linkFormShow.value = false;
      } catch (err) {
        const error = err as ApiError;
        $q.notify({
          type: 'negative',
          message: error.title,
        });
      }
    }
  });
}

function onLinkReset() {
  editLinkInfo.name = '';
  editLinkInfo.pid = '';
  editLinkInfo.mids = [];
  editLinkInfo.sids = [];
  linkForm.value?.resetValidation();
}

const midsOptions: OptionsItem[] = [];
function getAllPublish() {
  getPublishList().then((res) => {
    res.forEach((item) => {
      const obj = {
        label: item.name,
        value: item.id,
      };
      midsOptions.push(obj);
    });
  });
}
const sidsOptions: OptionsItem[] = [];
function getAllTrainSize() {
  getAllTrainSizeList().then((res) => {
    res.forEach((item) => {
      const obj = {
        label: item.name,
        value: item.id,
      };
      sidsOptions.push(obj);
    });
  });
}
</script>
