<!--
  * 入库单
  *
  * @Author:    霍锦
  * @Date:      2025-03-26 15:10:02
  * @Copyright  友仓
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="客户订单号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.customerNumber" placeholder="客户订单号"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch" class="smart-margin-left10">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" v-privilege="'asn:add'">
          <template #icon>
            <PlusOutlined/>
          </template>
          新建
        </a-button>
        <a-button @click="confirmBatchDelete" type="primary" danger v-privilege="'asn:batchDelete'"
                  :disabled="selectedRowKeyList.length == 0">
          <template #icon>
            <DeleteOutlined/>
          </template>
          批量删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.RECEIVE.ASN" :refresh="queryData"/>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        rowKey="asnId"
        bordered
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        @expand="querySubTableData"
    >
      <template #expandedRowRender="{ record }">
        <a-table
            size="small"
            :columns="subColumns"
            :data-source="subTableData"
            :pagination="false"
            rowKey="asnDetailId"
        >

          <template #summary>
            <a-table-summary-row style="font-weight: bold">
              <a-table-summary-cell :index="0" align="center">合计</a-table-summary-cell>
              <a-table-summary-cell :index="1">&nbsp;</a-table-summary-cell>
              <a-table-summary-cell :index="2" align="center">
                <a-typography-text type="danger">{{ totals.totalOrderQuantity }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell :index="3" align="center">
                <a-typography-text type="danger">{{ totals.totalReceivedQuantity }}</a-typography-text>
              </a-table-summary-cell>
            </a-table-summary-row>
          </template>
        </a-table>
      </template>

      <template #bodyCell="{ text, record, column }">

        <template v-if="column.dataIndex === 'orderType'">
          {{ $smartEnumPlugin.getDescByValue('ASN_ORDER_TYPE_ENUM', text) }}
        </template>

        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="getStatusColor(text)">
            {{ $smartEnumPlugin.getDescByValue('ASN_ORDER_STATUS_ENUM', text) }}
          </a-tag>
        </template>


        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link" v-privilege="'asn:update'">
              <template #icon>
                <EditOutlined/>
              </template>
              编辑
            </a-button>
            <a-button @click="onDelete(record)" danger type="link" v-privilege="'asn:delete'">
              <template #icon>
                <DeleteOutlined/>
              </template>
              删除
            </a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total:number) => `共${total}条`"
      />
    </div>

  </a-card>
</template>
<script setup lang="ts">
import {computed, reactive, ref, onMounted, watch} from 'vue';
import {message, Modal} from 'ant-design-vue';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {PAGE_SIZE_OPTIONS} from '/@/constants/common-const';
import {smartSentry} from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import {asnApi} from '/@/api/business/receive/asn/asn-api';
import {asnDetailApi} from '/@/api/business/receive/asnDetail/asn-detail-api'
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import {useRoute, useRouter} from "vue-router";

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '入库单id',
    dataIndex: 'asnId',
    ellipsis: true,
  },
  {
    title: '客户',
    dataIndex: 'customerName',
    ellipsis: true,
  },
  {
    title: '入库单号',
    dataIndex: 'asnNumber',
    ellipsis: true,
  },
  {
    title: '客户订单号',
    dataIndex: 'customerNumber',
    ellipsis: true,
  },
  {
    title: '单据类型',
    dataIndex: 'orderType',
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    ellipsis: true,
  },
  {
    title: '收货单位',
    dataIndex: 'name',
    ellipsis: true,
  },
  {
    title: '订单数量',
    dataIndex: 'orderQuantity',
    ellipsis: true,
  },
  {
    title: '收货数量',
    dataIndex: 'receivedQuantity',
    ellipsis: true,
  },
  {
    title: '订单日期',
    dataIndex: 'orderDate',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 140,
  },
]);

// 子表格列
const subColumns = [
  {
    title: '物料编码',
    dataIndex: 'itemCode',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '订单数量',
    align: 'center',
    dataIndex: 'orderQuantity',
    ellipsis: true,
  },
  {
    title: '收货数量',
    align: 'center',
    dataIndex: 'receivedQuantity',
    ellipsis: true,
  },
];


// 获取子表格数据
const subTableData = ref([]);

async function querySubTableData(expanded: boolean, record: any) {
  if (expanded && !record.children) {
    try {
      const res = await asnDetailApi.queryPage({asnId: record.asnId, pageNum: 1, pageSize: 100});
      subTableData.value = res.data.list;
    } catch (e) {
      smartSentry.captureError(e);
    }
  }
}

// 计算合计值
const totals = computed(() => {
  let totalOrderQuantity = 0;
  let totalReceivedQuantity = 0;

  subTableData.value.forEach(({orderQuantity, receivedQuantity}) => {
    totalOrderQuantity += orderQuantity;
    totalReceivedQuantity += receivedQuantity;
  });
  return {totalOrderQuantity, totalReceivedQuantity};
});


// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  customerNumber: undefined, //客户订单号
  pageNum: 1,
  pageSize: 10,
};
// 查询表单form
const queryForm = reactive({...queryFormState});
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 搜索
function onSearch() {
  queryForm.pageNum = 1;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await asnApi.queryPage(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// ---------------------------- 添加/修改 ----------------------------
let router = useRouter();

function showForm(data: any) {
  const id = Date.now().toString(); // 生成一个唯一标识符
  //将数据存储到sessionStorage中
  sessionStorage.setItem(id, JSON.stringify(data));
  router.push({
    path: '/receive/asn/asn-form',
    query: {
      id: id
    }
  });
}

// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete(data: object) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求删除
async function requestDelete(data: any) {
  SmartLoading.show();
  try {

    await asnApi.delete(data.asnId);
    message.success('删除成功');
    await queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys: any) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete();
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求批量删除
async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await asnApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    await queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

//根据不同状态显示不同颜色；orange green purple success processing error default warning
function getStatusColor(status: string) {
  // 根据不同的状态值返回不同的颜色
  switch (status) {
    case 'CREATED':
      return 'orange';
    case 'APPROVING':
      return 'cyan';
    case 'APPROVED':
      return 'purple';
    case 'IN_PROGRESS':
      return 'blue';
    case 'COMPLETED':
      return 'green';
    case 'CANCELLED':
      return 'red';
    default:
      return 'orange';
  }
}

//监听asn-form组件返回到当前组件自动刷新。
const route = useRoute();
watch(
    () => route.query,
    (newValue) => {
      if (newValue.refresh === '1') {
        queryData();
      }
    }
);

onMounted(queryData);
</script>

