<script setup lang="ts">
import { defineEmits, h, ref } from 'vue';
import { NIcon, useMessage } from 'naive-ui';
import {
  AddCircleOutline as AddIcon,
  ArrowUndoCircle as CashIcon,
  CheckmarkDoneCircleOutline as CheckIcon,
  CloseSharp as CloseIcon
} from '@vicons/ionicons5';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { fetchAddManageTaskOut, fetchGetInventoryOutAdd } from '@/service/api/taskmg';
import inIcon from '@/assets/imgs/出库.png';
import { useRouterPush } from '@/hooks/common/router';
import LybSearch from '../../views/exploitation/lvyuebiao/modules/lvyuebiao-search.vue'; // 表格数据初始化

const appStore = useAppStore();
const {
  columns,
  data,
  columnChecks,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetInventoryOutAdd,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'OrderQuantity',
      title: '库存数量',
      width: 70,
      align: 'center'
    },
    {
      key: 'OrderLineNumber',
      title: '订单+行号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseOrderNumber',
      title: '采购订单号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseOrderLineItem',
      title: '采购订单行项目号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseRequestNumber',
      title: '采购申请号',
      align: 'center',
      width: 100
    },
    {
      key: 'StockUnit',
      title: '库存单位',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialType',
      title: '物资类型',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectName',
      title: '项目名称',
      align: 'center',
      width: 200
    },
    {
      key: 'MaterialCode',
      title: '物料编码',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialName',
      title: '物资名称',
      align: 'center',
      width: 200
    },
    {
      key: 'MaterialUnit',
      title: '物料单位',
      align: 'center',
      width: 100
    },
    {
      key: 'SupplierName',
      title: '供应商名称',
      align: 'center',
      width: 150
    },
    {
      key: 'PlannedDeliveryDate',
      title: '计划交货日期',
      align: 'center',
      width: 100
    },
    {
      key: 'ERPSystemFactory',
      title: 'ERP系统工厂',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectCode',
      title: '项目编码',
      align: 'center',
      width: 100
    },
    {
      key: 'ContractUnitPrice',
      title: '签约单价(不含税)',
      align: 'center',
      width: 100
    },
    {
      key: 'ContractTotalPrice',
      title: '签约总价(不含税)',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectType',
      title: '项目类型',
      align: 'center',
      width: 100
    },
    {
      key: 'ProcurementMethod',
      title: '采购方式',
      align: 'center',
      width: 100
    },
    {
      key: 'MajorCategory',
      title: '大类',
      align: 'center',
      width: 100
    },
    {
      key: 'MiddleCategory',
      title: '中类',
      align: 'center',
      width: 100
    },
    {
      key: 'SubCategory',
      title: '小类',
      align: 'center',
      width: 100
    }
  ]
});

const message = useMessage();
const { checkedRowKeys } = useTableOperate(data, getData);

// 弹窗确认出库数量
const showModalRef = ref(false);
const emit = defineEmits<{
  (e: 'submitted'): void;
}>();

const renderIcon = () => {
  return h(NIcon, null, {
    default: () => h(CashIcon)
  });
};
const addIcon = () => {
  return h(NIcon, null, {
    default: () => h(AddIcon)
  });
};
const checkIcon = () => {
  return h(NIcon, null, {
    default: () => h(CheckIcon)
  });
};
// 缓存订单对应数量
const inputValues = ref<{ [key: string]: number }>({});

const checkData = ref<Api.Exploitation.PurchaseOrder[]>([]);
// 选择库存相关
const showDrawer = ref(false);
const confirmSelection = () => {
  checkedRowKeys.value.forEach(key => {
    const rowData = data.value.find(row => String(row.OrderLineNumber) === key);
    if (rowData) {
      const alreadyExists = checkData.value.some(item => item.OrderLineNumber === rowData.OrderLineNumber);
      if (!alreadyExists) {
        checkData.value.push(rowData);
        inputValues.value[rowData.OrderLineNumber as string] = rowData.OrderQuantity;
      } else {
        message.warning(`以下数据已存在，请勿重复添加：${rowData.OrderLineNumber}`);
      }
    }
  });

  showDrawer.value = false;
  showModalRef.value = true;
};
function showDrawerClick() {
  showDrawer.value = true;
  checkedRowKeys.value = [];
}

const showPlanning = () => {
  emit('submitted'); // 通知父组件关闭
};

// 为每个项动态添加 showMore 属性
const showMoreFlags = ref<boolean[]>(Array.from({ length: checkData.value.length }, () => false));

// 展开/收起更多信息
const toggleDetails = (index: number) => {
  showMoreFlags.value[index] = !showMoreFlags.value[index];
};

// 显示/隐藏更多内容
const showMore = (index: number) => {
  return showMoreFlags.value[index];
};
const renderIcon2 = () => {
  return h(NIcon, null, {
    default: () => h(CloseIcon)
  });
};
const Remove = (orderLineNumber: string) => {
  checkData.value = checkData.value.filter(item => item.OrderLineNumber !== orderLineNumber);
  if (orderLineNumber in inputValues.value) {
    Reflect.deleteProperty(inputValues.value, orderLineNumber);
  }
};
const { routerPushByKey } = useRouterPush();
// 提交数据
async function getdata() {
  if (Object.keys(inputValues.value).length <= 0) {
    message.error('没有制定任何出库任务！', { duration: 5000 });
    return;
  }
  const hasZeroValue = Object.values(inputValues.value).includes(0);
  if (hasZeroValue) {
    message.error('出库数量不能为0', { duration: 5000 });
    return;
  }
  const response = await fetchAddManageTaskOut(inputValues.value);
  if (response.data?.Status === 1) {
    message.info(response.data?.msg, { duration: 5000 });
    emit('submitted'); // 通知父组件关闭
    routerPushByKey('planmg_todowork');
  }
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard>
      <NPageHeader subtitle="制定出库任务计划">
        <template #title>
          <a>出库任务</a>
        </template>
        <template #avatar>
          <NAvatar class="avatars" :src="inIcon" />
        </template>
        <template #extra>
          <NSpace>
            <NButton strong :render-icon="renderIcon" @click="showPlanning">返回</NButton>
          </NSpace>
        </template>
      </NPageHeader>
    </NCard>
    <NCard class="amin2">
      <div class="amin_div">
        <NButton strong :render-icon="addIcon" @click="showDrawerClick">选择库存</NButton>
        <NPopconfirm :show-icon="false" @positive-click="getdata">
          <template #trigger>
            <NButton strong :render-icon="checkIcon" color="#286f4f">创建并执行任务</NButton>
          </template>
          确认创建出库任务？
        </NPopconfirm>
      </div>
    </NCard>
    <NDrawer v-model:show="showDrawer" title="选择库存订单" placement="bottom" :default-height="850">
      <LybSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
      <NCard title="库存 -- 履约表信息" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
        <template #header-extra>
          <TableHeaderOperationintask
            v-model:columns="columnChecks"
            :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading"
            @refresh="getData"
            @add="confirmSelection"
          />
        </template>
        <NDataTable
          v-model:checked-row-keys="checkedRowKeys"
          :columns="columns"
          :data="data"
          size="small"
          :flex-height="!appStore.isMobile"
          :scroll-x="3500"
          :loading="loading"
          remote
          :row-key="row => row.OrderLineNumber"
          :pagination="mobilePagination"
          class="amin sm:h-full"
        />
      </NCard>
    </NDrawer>
    <div class="modal-content">
      <NInfiniteScroll>
        <NCard v-for="(item, index) in checkData" :key="item.OrderLineNumber as string" class="NCard-item">
          <div class="data-item">
            <!-- 第一行显示的内容 -->
            <p class="data-row">
              <span>
                <span class="task-quantity">库存数量 :</span>
                {{ item.OrderQuantity }}
              </span>
              <span>
                <span class="task-quantity">订单+行号 :</span>
                {{ item.OrderLineNumber }}
              </span>
              <span>
                <span class="task-quantity">项目名称:</span>
                {{ item.ProjectName }}
              </span>
              <span>
                <span class="task-quantity">库存单位 :</span>
                {{ item.StockUnit }}
              </span>
              <span>
                <span class="task-quantity">物资类型 :</span>
                {{ item.MaterialType }}
              </span>
            </p>

            <!-- 其他行内容，初始时隐藏 -->
            <p v-if="showMore(index)" class="data-row">
              <span>
                <span class="task-quantity">供应商名称:</span>
                {{ item.SupplierName }}
              </span>
              <span>
                <span class="task-quantity">物资名称:</span>
                {{ item.MaterialName }}
              </span>
              <span>
                <span class="task-quantity">物料单位:</span>
                {{ item.MaterialUnit }}
              </span>
              <span>
                <span class="task-quantity">采购订单计划交货日期:</span>
                {{ item.PlannedDeliveryDate }}
              </span>
              <span>
                <span class="task-quantity">ERP系统工厂:</span>
                {{ item.ERPSystemFactory }}
              </span>
            </p>

            <p v-if="showMore(index)" class="data-row">
              <span>
                <span class="task-quantity">项目编码:</span>
                {{ item.ProjectCode }}
              </span>
              <span>
                <span class="task-quantity">签约单价(不含税):</span>
                {{ item.ContractUnitPrice }}
              </span>
              <span>
                <span class="task-quantity">签约总价(不含税):</span>
                {{ item.ContractTotalPrice }}
              </span>
              <span>
                <span class="task-quantity">项目类型:</span>
                {{ item.ProjectType }}
              </span>
              <span>
                <span class="task-quantity">采购方式:</span>
                {{ item.ProcurementMethod }}
              </span>
            </p>
            <p v-if="showMore(index)" class="data-row">
              <span>
                <span class="task-quantity">大类:</span>
                {{ item.MajorCategory }}
              </span>
              <span>
                <span class="task-quantity">中类:</span>
                {{ item.MiddleCategory }}
              </span>
              <span>
                <span class="task-quantity">小类:</span>
                {{ item.SubCategory }}
              </span>
              <span>
                <span class="task-quantity">物料编码:</span>
                {{ item.MaterialCode }}
              </span>
              <span></span>
            </p>
            <!-- 展开/收起按钮 -->
            <a class="data-row" @click="toggleDetails(index)">展开/收起</a>

            <div class="input-container">
              <div class="input-container2">
                <span>出库数量 :</span>
                <NInputNumber
                  v-model:value="inputValues[item.OrderLineNumber as string]"
                  min="1"
                  :max="item.OrderQuantity"
                  placeholder="任务数量"
                />
              </div>
              <NButton
                icon-placement="right"
                ghost
                :render-icon="renderIcon2"
                @click="Remove(item.OrderLineNumber as string)"
              >
                移除
              </NButton>
            </div>
          </div>
        </NCard>
      </NInfiniteScroll>
    </div>
  </div>
</template>

<style scoped>
.input-container2 {
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 控制元素之间的间距 */
}

.modal-content {
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  height: 600px; /* 使 modal 内容区域充满高度 */
}
.amin2 {
  height: 100%;
}
.amin {
  min-height: 730px;
}
.amin_div {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.avatars {
  background-color: transparent;
}

.data-item {
  margin: 20px;
}
.data-row {
  display: flex;
  gap: 10px; /* 控制间距 */
  margin-top: 15px;
}
.data-row span {
  flex: 1 1 20%; /* 平分宽度，给每个 span 设置相同的宽度，确保每个 span 占 20% */
  box-sizing: border-box;
}
.task-quantity {
  /* font-weight: bold; */
  color: #868686;
}

.input-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.input-label {
  margin-right: 10px;
}
.NCard-item {
  margin-bottom: 10px;
  /* background-color: #eaf4f0; */
  /* background: linear-gradient(to bottom, #eaf4f0, white); */
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.data-item a {
  cursor: pointer;
  margin-top: 20px;
  color: #868686;
  /* display: flex;
  justify-content: flex-end; */
}

.button-container {
  display: flex;
  justify-content: flex-end; /* 按钮靠右对齐 */
  gap: 10px; /* 按钮之间的间距 */
}

.NButton {
  flex: 0 1 auto; /* 防止按钮扩展填满容器 */
}
.card-container {
  margin-top: auto; /* 使 NCard 靠在底部 */
}
</style>
