<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout
        :model="state.queryData"
        ref="formRef"
        :rules="rules"
        label-position="left"
        :gutter="30"
      >
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="state.queryData.keyword" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="开始时间" prop="beginDate">
          <el-date-picker v-model="state.queryData.beginDate" clearable />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="state.queryData.endDate" clearable />
        </el-form-item>

        <template #buttonGroup>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="info" @click="onReset">重置</el-button>
        </template>
      </cacp-search-panel-layout>
    </template>
    <cacp-complex-table
      :actions="actions"
      :data="tableData"
      :pagination="tablePagination"
      :actionsWidth="100"
      @on-page-change="onPageChange"
      @on-size-change="onSizeChange"
      :loading="loading"
    >
      <el-table-column property="orderId" label="单据号" width="330" sortable />
      <el-table-column property="categoryCode" label="分类" width="120">
        <template #default="scope">{{ formatCategory(scope.row.categoryCode) }}</template>
      </el-table-column>
      <el-table-column property="orderAmount" label="数量" sortable width="120" />
      <el-table-column property="userName" label="创建人" width="120" sortable />
      <el-table-column property="createTime" label="创建时间" sortable min-width="200">
        <template #default="scope">{{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</template>
      </el-table-column>
    </cacp-complex-table>
  </cacp-search-layout>
  <cacp-dialog v-model="state.dialogVisible" title="新建单据" :resizable="false" width="360" @closed="onDialogClosed">
    <el-form
      :model="state.modifyFormData"
      ref="modifyFormRef"
      :rules="infoRules"
      label-width="auto"
      label-position="left"
    >
      <el-form-item label="分类" prop="categoryCode" required>
        <el-select v-model="state.modifyFormData.categoryCode">
          <el-option
            v-for="item in categoryInfoList"
            :key="item.categoryCode"
            :label="item.categoryName"
            :value="item.categoryCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="级别" prop="orderLevel" required>
        <el-select v-model="state.modifyFormData.orderLevel">
          <el-option v-for="item in levelList" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="orderAmount"
        ><el-input-number v-model="state.modifyFormData.orderAmount"></el-input-number
      ></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </template>
  </cacp-dialog>
</template>
<script setup lang="ts">
import { useLoading } from '@cacp/ui'
import { getOrderList, insertOrder, deleteOrder } from '@/apis/order'
import type { ListFormData } from '@/types/list'
import { type OrderInfo } from '@/types/order'
import { useCategoryStore, useLevelStore } from '@/stores'
import config from '@/config'

import dayjs from 'dayjs'

import {
  SuccessResultCode,
  useComplexTable,
  type Result,
  type SearchPanelLayoutInstance,
  type TableAction
} from '@cacp/ui'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, reactive, onBeforeMount } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'

interface State {
  queryData: ListFormData
  modifyFormData: OrderInfo
  dialogVisible: boolean
}
const { loading, setLoading } = useLoading()
const stores = useCategoryStore()
const { initCategory } = stores
const { categoryInfoList } = storeToRefs(stores)
const levelStores = useLevelStore()
const { initLevel } = levelStores
const { levelList } = storeToRefs(levelStores)
const tableHooks = useComplexTable<OrderInfo>(config)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = tableHooks
const router = useRouter()

const formRef = ref<SearchPanelLayoutInstance>()
const modifyFormRef = ref<FormInstance>()

const now = dayjs()

const state = reactive<State>({
  queryData: {
    keyword: '',
    beginDate: now.subtract(1, 'month').format('YYYY-MM-DD'),
    endDate: now.format('YYYY-MM-DD')
  },
  modifyFormData: {
    categoryCode: '',
    orderAmount: 1,
    orderLevel: '',
    orderId: '',
    parentId: '',
    userId: '',
    userName: '',
    createTime: '',
    accessoryList: []
  },
  dialogVisible: false
})

const rules = reactive<FormRules<ListFormData>>({
  beginDate: [{ required: true, message: '请输入开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请输入结束时间', trigger: 'change' }]
})

const infoRules = reactive<FormRules<OrderInfo>>({
  orderLevel: [{ required: true, message: '请选择级别', trigger: 'change' }],
  categoryCode: [{ required: true, message: '请选择分类', trigger: 'change' }]
})

const actions = <Array<TableAction>>[
  {
    key: '1',
    text: '新建',
    onclick: onCreate,
    limit: 'none',
    position: 'left',
    type: 'primary'
  },
  {
    key: '2',
    text: '查看',
    onclick: onView,
    limit: 'none',
    type: 'primary'
  },
  {
    key: '3',
    text: '删除',
    onclick: onDelete,
    confirm: true,
    limit: 'none',
    type: 'primary'
  }
]

function onSearch() {
  onPageChange(1)
}

function onReset() {
  formRef.value.resetFields()
  onPageChange(1)
}

function onCreate() {
  state.dialogVisible = true
}

function onDialogClosed() {
  const newForm = <OrderInfo>{
    categoryCode: '',
    orderAmount: 1,
    orderLevel: '',
    orderId: '',
    parentId: '',
    userId: '',
    userName: '',
    createTime: '',
    accessoryList: []
  }
  Object.assign(state.modifyFormData, newForm)
}

async function onDelete(row: OrderInfo) {
  const res = await deleteOrder(row.orderId)
  if (res.code == SuccessResultCode) {
    onPageChange(1)
  }
}

function onView(row: OrderInfo) {
  router.push({
    path: '/order-detail',
    query: {
      orderId: row.orderId
    }
  })
}

function onPageChange(page: number) {
  setPageIndex(page)
  onLoadData()
}
function onSizeChange(size: number) {
  setPageSizes(size)
  onLoadData()
}

// 取消
function onCancel() {
  state.dialogVisible = false
}
// 提交
function onSubmit() {
  modifyFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      const res: Result<number> = await insertOrder({ ...state.modifyFormData })
      if (res.code == SuccessResultCode) {
        state.dialogVisible = false
        onPageChange(1)
      }
    }
  })
}
// 格式化分类
function formatCategory(categoryCode: string): string {
  const result = categoryInfoList.value.find((item) => item.categoryCode == categoryCode)
  if (result) {
    return result.categoryName
  }
  return ''
}
// 加载数据
async function onLoadData() {
  const query = { ...state.queryData, pageIndex: tablePagination.currentPage, pageSize: tablePagination.pageSize }
  setLoading(true)
  const res = await getOrderList(query)
  if (res.code == SuccessResultCode) {
    setPagination(res.data)
  }
  setLoading(false)
}

onBeforeMount(async () => {
  initCategory()
  initLevel()
  onLoadData()
})
</script>
