<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:header-cell-name="props">
        <q-th :props="props">
          {{ props.col.label }}
          <q-icon name="edit" />
        </q-th>
      </template>
      <template v-slot:header-cell-code="props">
        <q-th :props="props">
          {{ props.col.label }}
          <q-icon name="edit" />
        </q-th>
      </template>

      <template v-slot:body-cell-name="props">
        <q-td :props="props" class="cursor-pointer">
          {{ props.row.name }}
          <q-popup-edit
            title="编辑名称"
            v-model="props.row.name"
            buttons
            :cover="false"
            :validate="caloriesRangeValidation"
            @hide="caloriesRangeValidation"
            @update:model-value="saveRowData(props.row)"
            v-slot="scope"
          >
            <q-input
              v-model="scope.value"
              hint="请输入名称！"
              :error="errorCalories"
              :error-message="errorMessageCalories"
              dense
              autofocus
              @keyup.enter="scope.set"
            />
          </q-popup-edit>
        </q-td>
      </template>
      <template v-slot:body-cell-code="props">
        <q-td :props="props" class="cursor-pointer">
          {{ props.row.code }}
          <q-popup-edit
            title="编辑编码"
            v-model="props.row.code"
            buttons
            :cover="false"
            :validate="caloriesRangeValidation"
            @hide="caloriesRangeValidation"
            @update:model-value="saveRowData(props.row)"
            v-slot="scope"
          >
            <q-input
              v-model="scope.value"
              hint="请输入编码！"
              :error="errorCalories"
              :error-message="errorMessageCalories"
              dense
              autofocus
              @keyup.enter="scope.set"
            />
          </q-popup-edit>
        </q-td>
      </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="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: 1400px; max-width: 80vw">
        <q-card-section>
          <div class="text-h6">编辑{{ editLinkInfo.name }}项目关联信息</div>
        </q-card-section>
        <q-card-section>
          <q-splitter v-model="splitterModel" :limits="[30, 70]">
            <template v-slot:before>
              <PublishManage
                :sizeHeight="600"
                :selects="editLinkInfo.mapInfoLinks || []"
                @selectsed="mapSelectsed"
              />
            </template>

            <template v-slot:after>
              <div class="q-pa-md">
                <TrainSizePage
                  :sizeHeight="600"
                  :selects="editLinkInfo.trainSizeLinks || []"
                  @selectsed="sizeSelectsed"
                />
              </div>
            </template>
          </q-splitter>
          <q-card-actions align="right">
            <q-btn color="primary" label="保存" @click="onLinkSave" />
            <q-btn label="取消" v-close-popup @click="onLinkReset" />
          </q-card-actions>
        </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,
} from '../api/ProjectApi';
import {
  saveProjectLink,
  getProjectLinkInfo,
  SaveLinkParams,
  LinkInfo,
  MapInfo,
  TrainSizeInfo,
} from '../api/ProjectLinkApi';
import { ApiError } from 'src/boot/axios';
import PublishManage from './PublishManage.vue';
import TrainSizePage from './TrainSizePage.vue';

const $q = useQuasar();

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

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

onMounted(() => {
  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: (row) => new Date(row.created_at).toLocaleString(),
    align: 'center',
  },
  {
    name: 'update_at',
    label: '更新时间',
    field: (row) => new Date(row.update_at).toLocaleString(),
    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: '',
});

interface LinkParams extends Omit<LinkInfo, 'pid' | 'code'> {
  name: string;
  pid: string;
}

const editLinkInfo = reactive<LinkParams>({
  name: '',
  pid: '',
  mapInfoLinks: [],
  trainSizeLinks: [],
});
function editLinkData(row: ProjectItem) {
  onLinkReset();
  getProjectLinkInfo(row.id)
    .then((res) => {
      editLinkInfo.name = res.name;
      editLinkInfo.pid = res.pid + '';
      editLinkInfo.mapInfoLinks = res.mapInfoLinks;
      editLinkInfo.trainSizeLinks = res.trainSizeLinks;
      linkFormShow.value = true;
    })
    .catch((err) => {
      const error = err as ApiError;
      $q.notify({
        type: 'negative',
        message: error.title,
      });
    });
}
const linkFormShow = ref(false);
async function onLinkSave() {
  try {
    const mids = editLinkInfo.mapInfoLinks?.map((item) => {
      return item.id;
    });
    const sids = editLinkInfo.trainSizeLinks?.map((item) => {
      return item.id;
    });
    const params: SaveLinkParams = {
      pid: +editLinkInfo.pid,
      mids: mids || [],
      sids: 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.mapInfoLinks = [];
  editLinkInfo.trainSizeLinks = [];
}

const errorCalories = ref(false);
const errorMessageCalories = ref('');
function caloriesRangeValidation(val?: string) {
  if (val !== undefined) {
    if (val.length == 0) {
      errorCalories.value = true;
      errorMessageCalories.value = '不能为空!';
      return false;
    }
  }
  errorCalories.value = false;
  errorMessageCalories.value = '';
  return true;
}

async function saveRowData(row: ProjectItem) {
  try {
    const params: createParams = {
      name: row.name,
      code: row.code,
    };
    await saveProjectData(row.id, params);
  } catch (err) {
    const error = err as ApiError;
    $q.notify({
      type: 'negative',
      message: error.title,
    });
  }
}

const splitterModel = ref(60);

function mapSelectsed(val: MapInfo[]) {
  editLinkInfo.mapInfoLinks = val;
}
function sizeSelectsed(val: TrainSizeInfo[]) {
  editLinkInfo.trainSizeLinks = val;
}
</script>
