<template>
  <div style="padding:10px">
    <q-card inline class="fit shadow-6">
      <q-card-main style="height:80%">
        <q-table
          ref="table"
          color="primary"
          :data="serverData"
          :columns="columns"
          separator="cell"
          selection="multiple"
          :selected.sync="selected"
          row-key="id"
          :pagination.sync="serverPagination"
          @request="request"
          :loading="loading"
          :rows-per-page-label="$t('Rows per page')"
          :rows-per-page-options="[5,10,20,30,40,50,60,200,500]"
          :no-data-label="$t('No data')"
        >
          <template slot="top-left" slot-scope="props">
            <q-input v-model="filter.name" type="text" prefix="菜单名称：" />
            &nbsp;&nbsp;
            <q-input v-model="filter.code" type="text" prefix="菜单编码：" />
            &nbsp;&nbsp;
            <q-btn push dense color="primary" icon="search" @click="search">{{ $t('Search') }}</q-btn>
            &nbsp;&nbsp;
            <q-btn push dense color="primary" icon="add" @click="gotoadd">{{$t('Add')}}</q-btn>&nbsp;&nbsp;
          </template>
          <template slot="top-right" slot-scope="props">
            <q-btn flat round dense :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" @click="props.toggleFullscreen" />
          </template>
          <template slot="top-selection" slot-scope="props">
            <q-btn icon="create" color="positive" label="启用" @click="updateStatusList(1)" />
            &nbsp;&nbsp;
            <q-btn icon="create" color="negative" label="停用" @click="updateStatusList(0)" />
          </template>
          <q-td slot="body-cell-status" slot-scope="props" :props="props">
            <q-chip :color="props.value === 1 ? 'positive' : 'negative'" text-color="white" small>
              {{ props.value === 1 ? '启用' : '停用' }}
            </q-chip>
          </q-td>
          <q-td slot="body-cell-id" slot-scope="props" :props="props" style="width:100px">
            <q-btn small round push glossy dense icon="edit" color="primary" @click="editMenu(props.value)"></q-btn>
            <q-btn small round push glossy dense icon="delete" color="red" :disabled="props.row.status=='1'" @click="delMenu(props.value)"></q-btn>
            <!-- <q-btn small round push glossy dense icon="arrow_upward" color="orange" @click="moveUp(props.value)" v-if="props.row.sortOrder > 1"></q-btn> -->
            <!-- <q-btn small round push glossy dense icon="arrow_downward" color="orange" @click="moveDown(props.value)"></q-btn> -->
          </q-td>
        </q-table>
      </q-card-main>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-modal v-model="dialog" :content-css="{minWidth: '70vw', minHeight: '80vh'}">
      <q-modal-layout>
        <q-toolbar slot="header">
          <q-toolbar-title>
            {{editMode ? '编辑菜单' : '新增菜单'}}
          </q-toolbar-title>
        </q-toolbar>
        <q-toolbar slot="footer">
          <q-toolbar-title></q-toolbar-title>
          <q-btn round  @click="dialog = false">取消</q-btn>
          <q-btn round color="red" @click="saveMenu">保存</q-btn>
        </q-toolbar>
        
        <div class="layout-padding">
          <q-field class="liststype" :error="$v.form.name.$error" error-label="菜单名称不能为空">
            <q-input v-model="form.name" float-label="菜单名称" />
          </q-field>
          <q-field class="liststype" :error="$v.form.code.$error" error-label="菜单编码不能为空且不能重复">
            <q-input v-model="form.code" float-label="菜单编码" />
          </q-field>
          <q-field class="liststype">
            <q-input v-model.number="form.sortOrder" float-label="排序序号" type="number" />
          </q-field>
          <q-field class="liststype">
            <q-select v-model="form.status" :options="statusOptions" float-label="状态" />
          </q-field>
        </div>
      </q-modal-layout>
    </q-modal>
  </div>
</template>

<script>
import { required } from 'vuelidate/lib/validators'
import {
  getMetroworkMenuList,
  getMetroworkMenu,
  saveMetroworkMenu,
  updateMetroworkMenu,
  deleteMetroworkMenu,
  enableMetroworkMenu,
  disableMetroworkMenu
} from '@/service/metroworkmenu/metroworkmenu'

export default {
  name: 'MetroworkMenu',
  data () {
    return {
      serverData: [],
      selected: [],
      loading: false,
      filter: {
        name: '',
        code: ''
      },
      columns: [
        {
          name: 'name',
          label: '菜单名称',
          field: 'name',
          align: 'left'
        },
        {
          name: 'code',
          label: '菜单编码',
          field: 'code',
          align: 'left'
        },
        {
          name: 'sortOrder',
          label: '排序',
          field: 'sortOrder',
          align: 'center'
        },
        {
          name: 'status',
          label: '状态',
          field: 'status',
          align: 'center'
        },
        {
          name: 'createTime',
          label: '创建时间',
          field: 'createTime',
          align: 'center',
          format: (val) => val ? new Date(val).toLocaleString() : ''
        },
        {
          name: 'id',
          label: '操作',
          field: 'id',
          align: 'center'
        }
      ],
      serverPagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 0
      },
      dialog: false,
      editMode: false,
      form: {
        id: null,
        name: '',
        code: '',
        sortOrder: 0,
        status: 1
      },
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '停用', value: 0 }
      ]
    }
  },
  validations: {
    form: {
      name: { required },
      code: { required }
    }
  },
  methods: {
    request (props) {
      this.loading = true
      let { page, rowsPerPage, sortBy, descending } = props.pagination
      let filter = props.filter

      getMetroworkMenuList({
        page: page,
        size: rowsPerPage,
        name: this.filter.name,
        code: this.filter.code
      }).then(response => {
        if (response.data.code === 200) {
          const data = response.data.data
          this.serverData = data.list || []
          this.serverPagination.rowsNumber = data.total || 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$q.notify({
          color: 'negative',
          message: '获取数据失败'
        })
      })
    },

    search () {
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      })
    },

    gotoadd () {
      this.editMode = false
      this.form = {
        id: null,
        name: '',
        code: '',
        sortOrder: 0,
        status: 1
      }
      this.dialog = true
    },

    editMenu (id) {
      getMetroworkMenu(id).then(response => {
        if (response.data.code === 200) {
          this.form = { ...response.data.data }
          this.editMode = true
          this.dialog = true
        }
      })
    },

    saveMenu () {
      this.$v.form.$touch()
      if (this.$v.form.$error) {
        return
      }

      const apiMethod = this.editMode ? updateMetroworkMenu : saveMetroworkMenu

      apiMethod(this.form).then(response => {
        if (response.data.code === 200) {
          this.$q.notify({
            color: 'positive',
            message: this.editMode ? '更新成功' : '新增成功'
          })
          this.dialog = false
          this.request({
            pagination: this.serverPagination,
            filter: this.filter
          })
        } else {
          this.$q.notify({
            color: 'negative',
            message: response.data.message || '操作失败'
          })
        }
      })
    },

    async delMenu (id) {
      try {
        await this.$q.dialog({
          title: '确认删除',
          message: '确定要删除这个菜单吗？',
          cancel: '取消',
          ok: '确定',
          persistent: true
        });

        const response = await deleteMetroworkMenu(id);
        if (response.data.code === 200) {
          this.$q.notify({
            color: 'positive',
            message: '删除成功'
          });
          this.request({
            pagination: this.serverPagination,
            filter: this.filter
          });
        }
      } catch (error) {
        // 用户点击了取消按钮，忽略错误
      }
    },

    async updateStatusList (status) {
      if (this.selected.length === 0) {
        this.$q.notify({
          color: 'negative',
          message: '请选择要操作的菜单'
        })
        return
      }

      const action = status === 1 ? '启用' : '停用'

      try {
        await this.$q.dialog({
          title: '确认' + action,
          message: `确定要${action}选中的菜单吗？`,
          cancel: '取消',
          ok: '确定',
          persistent: true
        });

        const promises = this.selected.map(item => {
          const apiMethod = status === 1 ? enableMetroworkMenu : disableMetroworkMenu
          return apiMethod(item.id)
        })

        await Promise.all(promises)

        this.$q.notify({
          color: 'positive',
          message: action + '成功'
        })
        this.selected = []
        this.request({
          pagination: this.serverPagination,
          filter: this.filter
        })
      } catch (error) {
        // 用户点击了取消按钮，忽略错误
      }
    },

    moveUp (id) {
      // 上移逻辑
      this.updateSortOrder(id, -1)
    },

    moveDown (id) {
      // 下移逻辑
      this.updateSortOrder(id, 1)
    },

    updateSortOrder (id, offset) {
      // 这里可以实现排序调整逻辑
      // 可以通过调用后端API来更新排序
      this.$q.notify({
        color: 'info',
        message: '排序功能开发中'
      })
    }
  },

  mounted () {
    this.request({
      pagination: this.serverPagination,
      filter: this.filter
    })
  }
}
</script>

<style scoped>
.q-table tbody td {
  font-size: 14px;
}
</style>
