<template>
  <div class="gi_table_page">
    <GiTable
        row-key="id"
        :data="dataList"
        :columns="columns"
        :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 1600 }"
        :pagination="pagination"
        :disabled-tools="['size']"
        :disabled-column-keys="['name']"
        :selected-keys="selectedKeys"
        :row-selection="{ type: 'checkbox', showCheckedAll: true }"
        @select-all="selectAll"
        @select="select"
        @refresh="search"
    >
      <template #toolbar-left>
        <a-input-search v-model="queryForm.userName" placeholder="请输入姓名" allow-clear @search="search" />
        <a-input-search v-model="queryForm.carNo" placeholder="请输入人员卡号" allow-clear @search="search" />
	      <a-input-search v-model="queryForm.orderNo" placeholder="请输入任务工单号" allow-clear @search="search" />
        <a-input-search v-model="queryForm.materialName" placeholder="请输入物料名称" allow-clear @search="search" />
        <a-input-search v-model="queryForm.encoding" placeholder="请输入物料编码" allow-clear @search="search" />
        <a-date-picker
          v-model="queryForm.startDate"
          placeholder="请选择开始时间"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          style="height: 32px"
          @change="search"
        />
        <a-date-picker
          v-model="queryForm.endDate"
          placeholder="请选择结束时间"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          style="height: 32px"
          @change="search"
        />

        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['workOrder:record:delete']" type="outline" status="danger" @click="onDelete">
          <template #icon><icon-delete /></template>
          <template #default>删除</template>
        </a-button>
        <a-button v-permission="['workOrder:record:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>

      <template #photoUrl="{ record }">
        <a-image :src="record.photoUrl" width="55" />
      </template>
      <template #unitWeight="{ record }">
        {{ record.unitWeight + 'g' }}
      </template>
      <template #totalWeight="{ record }">
        {{ record.totalWeight + 'g' }}
      </template>

      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['workOrder:record:detail']" title="详情" @click="onDetail(record)">详情</a-link>
          <a-link v-permission="['workOrder:record:delete']" status="danger" :title="'删除'" @click="onDeleteOne(record.id)">删除</a-link>
        </a-space>
      </template>
    </GiTable>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:visible="detailModalVisible"
      title="称重详情"
      width="800px"
      :loading="detailLoading"
    >
      <GiTable
        v-if="detailData.length > 0"
        row-key="id"
        :data="detailData"
        :columns="detailColumns"
        :scroll="{ x: '100%', y: '100%', minWidth: 700 }"
      >
        <template #imgUrl="{ record }">
          <a-image :src="record.imgUrl" width="50" />
        </template>
        <template #calculatedWeight="{ record }">
          {{ record.calculatedWeight + 'g' }}
        </template>
        <template #weight="{ record }">
          {{ record.weight + 'g' }}
        </template>
      </GiTable>
      <div v-else class="no-data">
        <icon-loading style="font-size: 48px; color: rgb(var(--arcoblue-6));" />
        <p>暂无称重数据</p>
      </div>
    </a-modal>

  </div>
</template>

<script setup lang="ts">
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { useDownload, useTable } from '@/hooks'
import { isMobile } from '@/utils'
import has from '@/utils/has'
import type GiTable from "@/components/GiTable/index.vue";
import {ref, reactive} from "vue";
import {Message} from "@arco-design/web-vue";
import {
  deleteWorkOrder,
  exportWorkOrder, getWorkOrder,
  listWorkOrder,
  type WorkOrderQuery,
  type WorkOrderResp
} from "@/apis/workOrder/workOrder";

defineOptions({ name: 'Record' })



const queryForm = reactive<WorkOrderQuery>({
  orderNo: undefined,
  materialName: undefined,
  encoding: undefined,
  userName: undefined,
  carNo: undefined,
  startDate: undefined,
  endDate: undefined,
  sort: ['w.id,desc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  selectedKeys,
  select,
  selectAll,
  search,
  handleDelete,
} = useTable((page) => listWorkOrder({ ...queryForm, ...page }), { immediate: true })

// 创建工具函数统一处理列配置
const processColumns = (columns: TableInstanceColumns[]): TableInstanceColumns[] => {
  return columns.map(column => {
    const defaultConfig = {
      ellipsis: true,
      tooltip: true
    };
    return { ...defaultConfig, ...column };
  });
};

// 定义列配置，使用工具函数处理
const columns = ref<TableInstanceColumns[]>(processColumns([
  { title: '标题', dataIndex: 'title', width: 180 },
  { title: '创建人', dataIndex: 'createUserString' },
  { title: '人员卡号', dataIndex: 'cardNo' },
  { title: '任务工单号', dataIndex: 'orderNo' },
  { title: '物料图片', dataIndex: 'photoUrl', slotName: 'photoUrl', minWidth: 180, ellipsis: true, tooltip: true },
  { title: '物料名称', dataIndex: 'materialName' },
  { title: '物料编码', dataIndex: 'encoding' },
  { title: '单位克重', dataIndex: 'unitWeight' ,slotName: 'unitWeight'},
  { title: '总重量', dataIndex: 'totalWeight' ,slotName: 'totalWeight'},
  { title: '称重次数', dataIndex: 'totalCount' },
  { title: '创建时间', dataIndex: 'createTime', width: 180 },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['workOrder:record:detail', 'workOrder:record:update', 'workOrder:record:delete'])
  }
]))

// 重置
const reset = () => {
  queryForm.orderNo = undefined
  queryForm.materialName = undefined
  queryForm.encoding = undefined
  queryForm.userName = undefined
  queryForm.carNo = undefined
  queryForm.startDate = undefined
  queryForm.endDate = undefined
  search()
}

// 详情弹窗状态
const detailModalVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<any[]>([])

// 详情列配置
const detailColumns = ref<TableInstanceColumns[]>([
  { title: '称重次数', dataIndex: 'weightTime' },
  { title: '物料名称', dataIndex: 'materialName' },
  { title: '数量', dataIndex: 'quantity' },
  { title: '重量', dataIndex: 'weight', slotName: 'weight' },
  { title: '计算重量', dataIndex: 'calculatedWeight', slotName: 'calculatedWeight' },
  { title: '抓拍图片', dataIndex: 'imgUrl', slotName: 'imgUrl' }
])

// 详情
const onDetail = async (record: WorkOrderResp) => {
  detailLoading.value = true
  detailModalVisible.value = true
  detailData.value = []

  getWorkOrder(record.id).then(res => {
    if (res.code == '0') {
      detailData.value = res.data;
      detailLoading.value = false
    } else {
      Message.error('获取详情失败')
    }
  });
};

// 删除
const onDeleteOne = (id) => {
  return handleDelete(() => deleteWorkOrder(id), {
    content: `是否确定删除该条数据？`,
    showModal: true
  })
}

// 删除
const onDelete = () => {
  if (!selectedKeys.value.length) {
    return Message.warning('请选择数据')
  }
  return handleDelete(() => deleteWorkOrder(selectedKeys.value), {
    content: `是否确定删除选中的 ${selectedKeys.value.length} 条数据？`,
    showModal: true
  })
}

// 导出
const onExport = () => {
  useDownload(() => exportWorkOrder(queryForm))
}

</script>

<style scoped lang="scss">
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--color-text-4);
  
  p {
    margin-top: 16px;
    font-size: 14px;
  }
}
</style>