<template>
  <package-form v-if="showForm" :cateTree="cateTree" :cateId="cateId" :data="projectPackage" @close="showForm = false"
    @change="getList()" />
  <div v-show="!showForm" v-loading="loading" class="flex h-full bg-white">
    <div class="flex-shrink-0 w-3/10 min-w-240px max-w-320px border-r border-gray-200 h-full">
      <classify-list v-bind="componentProps" :checked-cate="current" :data="cateList" @change="changeCurrent($event)"
        @search="getCateList()">
        <template #header>
          <div class="text-20px font-semibold pb-15px">套餐管理</div>
        </template>
      </classify-list>
    </div>
    <div class="flex-grow h-full bg-white">
      <my-layout>
        <layout-item>
          <div class="p-15px flex">
            <el-input v-model="name" class="w-160px mr-15px" placeholder="请输入套餐名称搜索" clearable @keyup.enter="search"
              @input="changeName" />
            <el-select v-model="packageType" clearable class="w-160px mr-15px" placeholder="所有组合类型">
              <el-option v-for="item in ProjectPackageType" :label="item.label" :value="item.value" />
            </el-select>
            <el-button type="primary" @click="search()">查询</el-button>
            <el-button style="margin-left: auto" type="primary" @click="edit()">新增套餐</el-button>
          </div>
        </layout-item>
        <layout-main :scroll="false">
          <el-table height="100%" :data="list">
            <el-table-column :min-width="240" label="套餐名称">
              <template #default="{ row: { name } }">
                <el-tooltip :disabled="!name" :content="name" placement="top-start" effect="light">
                  <div class="truncate">{{ name || "" }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column :min-width="160" label="套餐价格">
              <template #default="{ row: { priceStr } }">
                <div v-if="priceStr" class="truncate">￥{{ priceStr }}</div>
              </template>
            </el-table-column>
            <el-table-column :min-width="160" label="套餐有效期">
              <template #default="{ row: { validDays,hasValidDays } }">
                <div v-if="hasValidDays" class="truncate">{{ validDays }}天</div>
              </template>
            </el-table-column>
            <el-table-column width="120" label="组合形式">
              <template #default="{ row: { packageType } }">
                <div class="truncate">{{ ProjectPackageTypeMap[packageType] }}</div>
              </template>
            </el-table-column>
            <el-table-column width="100" label="套餐状态">
              <template #default="{ row: { enable } }">
                <div class="truncate">{{ enable ?'启用':'停用' }}</div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" class-name="el-table-fixed-column--shadow" label="操作" width="180">
              <template #default="{row}">
                <el-text v-if="row.enable" class="cursor-pointer mr-2" type="primary"
                  @click="toggleEnable(row,false)">停用</el-text>
                <el-text v-else type="primary" class="cursor-pointer mr-2" @click="toggleEnable(row,true)">启用</el-text>
                <el-text type="primary" class="cursor-pointer mr-2" @click="edit(row)">编辑</el-text>
                <el-text type="primary" class="cursor-pointer" @click="show(row)">详情</el-text>

              </template>
            </el-table-column>
          </el-table>
        </layout-main>
        <layout-item>
          <pagination :bgWhite="false" :totalRow="total" :pageSize="pageSize" :currentPage="page"
            @handle-size-change="changeSize" @handle-current-change="changePage" />
        </layout-item>
      </my-layout>
      <package-detail-modal :data="packageDetail" :visible="detailVisible" :width="detailWidth"
        @close="closeDetailModal" />

    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { addProjectPackageCate, updateProjectPackageCate, setProjectPackageEnable, deleteProjectPackageCate, getProjectPackageCateList, sortProjectPackageCate, getProjectPackageList } from '@/api/member'
import { ProjectPackageType, ProjectPackageTypeMap } from "@/baseData";
import useElPagination from "@/hooks/useElPagination";
import useModal from "@/hooks/useModal";
import { memberStore } from "@/store/member";
import { tagsStore } from "@/store/tags";

import useClassifyList from "@/components/classify-list/useClassifyList";

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import classifyList from "@/components/classify-list/classify-list.vue";
import packageForm from "./package-form.vue";
import packageDetailModal from '@/components/package-detail-modal/package-detail-modal.vue'

const router = useRouter();
const name = ref("");
const packageType = ref('');
const list = ref([]);
const total = ref(0);
const loading = ref(false);
const { page, pageSize, changePage, changeSize } = useElPagination(getList);
const { memberInfo } = storeToRefs(memberStore());
const showForm = ref(false);
const projectPackage = ref({})
const { close: closeDetailModal, show: showDetailModal, visible: detailVisible, width: detailWidth } = useModal(800);
const packageDetail = ref({})

const options = {
  add: addProjectPackageCate,
  remove: deleteProjectPackageCate,
  update: updateProjectPackageCate,
  sort: sortProjectPackageCate,
  getList: getProjectPackageCateList,
  callback: () => changePage(1),
  loading: loading,
};
const cateId = ref('')

const { cateList, cateTree, current, getCateList, changeCurrent, componentProps } = useClassifyList(options);

function changeName(e) {
  if (e === "") search();
}

const currentParams = {};
function search() {
  currentParams.name = name.value.trim();
  currentParams.packageType = packageType.value;
  changePage(1);
}

async function getList() {
  loading.value = true;
  if (current.value._id) {
    const childrenIds = Array.isArray(current.value.childrenIds) ? [current.value._id, ...(current.value.childrenIds || [])] : [current.value._id];
    const {
      success,
      message,
      data
    } = await getProjectPackageList({
      page: page.value,
      pageSize: pageSize.value,
      classIds: childrenIds,
      corpId: memberInfo.value.corpId,
      ...currentParams,
    });
    const { list: tableData = [], total: count = 0 } = data;
    list.value = Array.isArray(tableData) ? tableData.map(i => ({
      ...i,
      priceStr: i.packagePrice >= 0 ? Number(i.packagePrice).toFixed(2) : '',
    })) : [];
    total.value = count;
    loading.value = false;
    if (!success) ElMessage.error(message);
  } else {
    list.value = [];
    total.value = 0;
  }
  loading.value = false;

}
// getList();

function edit(item = {}) {
  cateId.value = (item._id ? item.cateId : current.value._id) || '';
  projectPackage.value = item;
  showForm.value = true;
}

function show(detail) {
  packageDetail.value = detail
  showDetailModal()
}

async function toggleEnable(row, bool) {
  await ElMessageBox.confirm(`确定${bool ? "启用" : "停用"}该套餐吗?`, "提示", { type: "warning", confirmButtonText: `确定${bool ? "启用" : "停用"}` });
  const res = await setProjectPackageEnable({ corpId: memberInfo.value.corpId, id: row._id, enable: bool });
  if (res.success) {
    ElMessage.success(`${bool ? "启用" : "停用"}成功`);
    getList();
  } else {
    ElMessage.error(res.message);
  }
}


async function remove({ _id }) {
  await ElMessageBox.confirm("确定删除该SOP吗?", "提示", { type: "warning" });
}

</script>
