<template>
  <div class="app-container">
    <!-- 列表 -->
    <!-- 搜索 -->
    <page-search ref="searchRef" :search-config="searchConfig" @query-click="newHandleQueryClick"
      @reset-click="handleResetClick" />
    <!-- 统计 -->
    <data-tongji :data="gongjiData" />
    <!-- 列表 -->
    <page-content ref="contentRef" :content-config="contentConfig" @add-click="handleAddClick"
      @edit-click="handleEditClick" @export-click="handleExportClick" @search-click="handleSearchClick"
      @toolbar-click="handleToolbarClick" @operat-click="handleOperatClick" @filter-change="handleFilterChange">
      <template #stockNumber="scope">
        <div class="columne">
          <div class="center">
            <el-text>第一单位</el-text>
            <el-text>{{ scope.row.stockNumber }}/{{ scope.row.conUnit }}</el-text>
          </div>
          <div class="center" v-if="scope.row.conUnitTwo">
            <el-text>第二单位</el-text>
            <el-text>{{ scope.row.stockNumber / scope.row.conUnitTwoConvert }}/{{ scope.row.conUnitTwo }}</el-text>
          </div>
          <div class="center" v-else>
            <el-text type="info">未设置第二单位</el-text>
          </div>
        </div>
      </template>
      <template #isStock="scope">
        <el-switch v-model="scope.row.isStock" :active-value="1" :inactive-value="0"
          @click="isStockChange($event, scope.row)"></el-switch>
      </template>
      <template #status="scope">
        <el-tag :type="scope.row[scope.prop] == 1 ? 'success' : 'info'">
          {{ scope.row[scope.prop] == 1 ? "启用" : "禁用" }}
        </el-tag>
      </template>
      <template #conUnit="scope">
        <span>{{ scope.row.conUnit }}</span>
      </template>
      <template #goods="scope">
        <div class="goodslang">
          <div class="goods-list">
            <el-button v-for="item in scope.row.productList" :key="item.productId" type="text"
              @click="toGoods(item.id)">
              {{ item.name }}
            </el-button>
            <span v-if="scope.row.productList.length > 1">,</span>
          </div>
          <el-dropdown v-if="scope.row.productList.length > 1" trigger="click" @command="toGoods">
            <span class="el-dropdown-link" style="color: blue">
              <el-icon>
                <CaretBottom />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="item in scope.row.productList" :key="item.id" class="clearfix"
                  :command="item.id">
                  {{ item.name }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>

      <template #options="scope">
        {{ returnOptionsLabel(scope.prop, scope.row[scope.prop]) }}
      </template>
      <template #state="scope">
        <el-tag :type="returnStateType(scope.row[scope.prop])">
          {{ returnOptionsLabel(scope.prop, scope.row[scope.prop]) }}
        </el-tag>
      </template>
      <template #mobile="scope">
        <el-text>{{ scope.row[scope.prop] }}</el-text>
        <copy-button v-if="scope.row[scope.prop]" :text="scope.row[scope.prop]" style="margin-left: 2px" />
      </template>
      <template #operate="scope">
        <div style="
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          ">
          <el-button v-if="!isSyncStatus()" type="primary" link @click="refAddHaocaiOpen(scope.row)">
            编辑
          </el-button>
          <el-button link type="primary" @click="refAddHaocaiTakinShow(scope.row, 'consumables')">
            耗材盘点
          </el-button>
          <el-button link type="primary" @click="refAddHaocaiTakinShow(scope.row, 'manual-in')">
            入库记录
          </el-button>
          <!-- <el-button link type="primary" @click="refAddHaocaiTakinShow(scope.row, 'delete')">
            删除
          </el-button> -->
        </div>
      </template>
    </page-content>
    <!-- 耗材添加编辑 -->
    <add-haocai ref="refAddHaocai" @refresh="refresh" />
    <!-- 耗材盘点 -->
    <addConsTakin ref="refAddHaocaiTakin" @success="refresh" />
    <!-- AI入库 -->
    <ai-entry-dialog ref="aiEntryDialogRef" @update="
      contentRef?.fetchPageData()" />
  </div>
</template>

<script setup lang="ts">
import aiEntryDialog from "./components/aiEntryDialog.vue";
import addHaocai from "./components/add-haocai.vue";
import dataTongji from "./components/DataStatistics.vue";
import addConsTakin from "./components/addConsTakin.vue";
import consApi from "@/api/product/cons";
import UserAPI from "@/api/product/index";

import type { IObject, IOperatData } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import contentConfig from "./config/content";
import editModalConfig from "./config/edit";
import searchConfig from "./config/search";
import { returnOptionsLabel } from "./config/config";
import { isSyncStatus } from "@/utils/index";

const aiEntryDialogRef = ref<any>(null);

function showAiEntryDialog() {
  aiEntryDialogRef.value?.show?.();
}

const router = useRouter();
const {
  searchRef,
  contentRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  handleSubmitClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage();

async function isStockChange(e, row) {
  // console.log('isStockChange.e', e);
  // console.log('isStockChange.row', row);
  await consApi.edit(row)
}

function toGoods(id: number | string) {
  router.push({ path: "/product/index", query: { id: id } });
}

// 默认初始数据
const route = useRoute();
const { conName } = route.query;
if (conName) {
  contentConfig.indexActionData = { conName };
  if (conName) {
    searchConfig.formItems[1].initialValue = conName;
  }
}

if (isSyncStatus()) {
  contentConfig.toolbar[0].hidden = true;
  contentConfig.toolbar[1].hidden = false;
} else {
  contentConfig.toolbar[0].hidden = false;
  contentConfig.toolbar[1].hidden = true;
}

//统计数据
const gongjiData = reactive({ totalRow: 0 });
function getTongji(params: IObject | undefined) {
  const query = { ...params };
  if (params?.createAt) {
    query.beginTime = params.createAt[0];
    query.endTime = params.createAt[1];
    delete query.createAt;
  }
  consApi.statistics(query).then((res) => {
    Object.assign(gongjiData, res);
  });
}

function newHandleQueryClick(e: IObject | undefined) {
  const filterParams = contentRef.value?.getFilterParams();
  contentRef.value?.fetchPageData({ ...e, ...filterParams }, true);
  getTongji(e);
}

watch(
  () => contentRef.value?.pagination.total,
  (newval) => {
    gongjiData.totalRow = newval as number;
  }
);

//耗材盘点
const refAddHaocaiTakin = ref<any>(null);
function refAddHaocaiTakinShow(item: any, type: string) {
  console.log(item);
  if (type === "manual-in") {
    router.push({ path: "/inventory/libraryrecords", query: { inOutItem: type, conId: item.id } });
    return;
  }
  if (type === "delete") {
    refAddHaocaiTakin.value?.show?.(item, type);
    return;
  }
  if (type === "consumables") {
    refAddHaocaiTakin.value?.show?.(item, type);
    return;
  }
  refAddHaocaiTakin.value?.show?.(item);
}

function refresh() {
  console.log("refresh");
  contentRef.value?.fetchPageData();
  getTongji(undefined);
}
const refAddHaocai = ref<any>(null);
function refAddHaocaiOpen(item: any) {
  refAddHaocai.value?.open?.(item);
}
// 新增
async function handleAddClick() {
  refAddHaocaiOpen(undefined);
}
// 编辑
async function handleEditClick(row: IObject) {
  editModalRef.value?.handleDisabled(false);
  editModalRef.value?.setModalVisible();
  console.log({ ...row });
  editModalRef.value?.setFormData({ ...row, url: [row.url] });
}
// 其他工具栏
async function handleToolbarClick(name: string) {
  console.log(name);
  if (name === "sync") {
    let res = await UserAPI.sync();
    ElMessage.success("操作成功，数据正在后台同步中...");
    return;
  }
  if (name === "category") {
    router.push({ path: "/inventory/classification" });
    return;
  }
  if (name == "gongyinsahng") {
    router.push({ path: "/inventory/supplier" });
    return;
  }
  if (name == "ruku") {
    router.push({ path: "/inventory/operation_in" });
    return;
  }
  if (name == "chuku") {
    router.push({ path: "/inventory/operation_in", query: { type: "out" } });
    return;
  }
  if (name == "reportinglosses") {
    router.push({ path: "/inventory/operation_in", query: { type: "reportinglosses" } });
    return;
  }
  if (name == "damage-out" || name == "manual-out" || name == "manual-in") {
    router.push({ path: "/inventory/libraryrecords", query: { inOutItem: name } });
    return;
  }
  if (name === "batchWarehousing") {
    showAiEntryDialog();
    return;
  }
}
// 其他操作列
async function handleOperatClick(data: IOperatData) {
  console.log(data);
  if (data.name === "detail") {
    return;
  }
  if (data.name === "printer") {
  }
}

function returnStateType(status: string) {
  if (status === "unpaid") {
    return "warning";
  }
  if (status === "done") {
    return "primary";
  }
  if (status === "cancelled") {
    return "info";
  }
  if (status === "refund") {
    return "danger";
  }
}

onMounted(() => {
  getTongji({});
});
</script>

<style scoped lang="scss">
.center {
  display: flex;
  gap: 10px;
}

.goodslang {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .goods-list {
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //溢出用省略号显示
    white-space: nowrap; //溢出不换行
  }

  :deep(.goods-list .el-button--text span) {
    display: block;
    text-align: left;
  }

  :deep(.goods-list .el-button--text) {
    white-space: break-spaces;
  }
}
</style>
