<template>
  <div bg-fff flex class="h-full">
    <div h-full flex-shrink-0 class="w-3/10 min-w-240px max-w-320px border-r border-gray-200">
      <classify-list custom v-bind="componentProps" :level="4" :checked-cate="current" :data="cateList"
        :label-option="setLabel" @change="changeCurrent($event)" @search="getCateList()" @onHandle="handleCate($event)">
        <template #prepend>
          <div class="mt-15px pl-10px text-14px cursor-pointer hover:text-blue-500"
            :class="current.$type === 'all' ? 'text-blue-500' : 'text-gray-600'" @click="getAll()">
            全部项目
          </div>
        </template>
      </classify-list>
    </div>
    <div h-full flex-grow>
      <my-layout>
        <layout-item>
          <div p-15 class="flex items-center justify-between">
            <div class="flex items-center">
              <el-input :prefix-icon="Search" placeholder="搜索项目" v-model="projectName"></el-input>
              <el-button class="w-100px ml-10px" type="primary" @click="getList">搜索</el-button>
            </div>
            <el-button w-100px :icon="Plus" type="primary" @click="addProject">新增</el-button>
          </div>
        </layout-item>
        <layout-main :scroll="false">
          <el-table stripe height="100%" :data="newList" v-loading="loading">
            <el-table-column prop="projectName" label="项目名称" :min-width="120" />
            <el-table-column prop="projectTypeName" label="类型" :min-width="100"></el-table-column>
            <el-table-column prop="projectNo" label="编号" :min-width="100"></el-table-column>
            <el-table-column prop="unit" label="单位" :min-width="100"></el-table-column>
            <el-table-column prop="price" label="单价" :min-width="100">
              <template #default="{ row:{price } }">
                {{ price >= 0 ? (price - 0).toFixed(2) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="生成治疗单" :width="100">
              <template #default="{ row: {createTreatmentOrder} }">
                {{ createTreatmentOrder ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="关联治疗科室" :min-width="100">
              <template #default="{ row }">
                <el-tooltip :disabled="!row.deptNames" placement="top" effect="light" :content="row.deptNames">
                  <div class="truncate">{{ row.deptNames }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="projectStatusName" label="项目状态" :min-width="100"></el-table-column>
            <el-table-column fixed="right" class-name="el-table-fixed-column--shadow" label="操作" width="120">
              <template #default="{ row }">
                <el-text class="cursor-pointer mr-5px" type="primary" v-if="row.projectStatus === 'disable'"
                  @click="changeStatus(row)">启用</el-text>
                <el-text class="cursor-pointer mr-5px" type="danger" v-if="row.projectStatus === 'enable'"
                  @click="changeStatus(row)">停用</el-text>
                <el-text class="cursor-pointer mr-5px" type="primary" @click="eidt(row)">编辑</el-text>
              </template>
            </el-table-column>
          </el-table>
        </layout-main>
        <layout-item>
          <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
            @handle-current-change="changePage" />
        </layout-item>
      </my-layout>
    </div>
  </div>
  <project-cate-modal :data="currentCate" :visible="visibleCateModal" :width="widthCateModal" @change="onCateChange()"
    @close="closeCateModal" />
  <project-modal :visible="visible" :width="width" @close="close" :cateList="cateList" :cateTree="cateTree"
    @success="getList" :cateId="current._id" :project="project" />

</template>
<script setup>
import { computed, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getProjectList, addProjectCate, deleteProjectCate, getProjectCateList, updateProjectCate, sortProjectCate, updateProject, getProjectAllCount } from "@/api/project-manage";
import useModal from "@/hooks/useModal";
import { ProjectType } from "@/baseData";
import { Plus, Search } from "@element-plus/icons-vue";
import useClassifyList from "@/components/classify-list/useClassifyList";
import useElPagination from "@/hooks/useElPagination";

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import classifyList from "@/components/classify-list/classify-list.vue";
import projectModal from "./project-modal.vue";
import projectCateModal from "./project-cate-modal.vue";

const { close, show, visible, width } = useModal(800);
const { close: closeCateModal, show: showCateModal, visible: visibleCateModal, width: widthCateModal } = useModal(640);

const list = ref([]);
const total = ref(0);
const loading = ref(false);
const projectName = ref("");
const currentCate = ref({})
const options = {
  add: addProjectCate,
  remove: deleteProjectCate,
  update: updateProjectCate,
  sort: sortProjectCate,
  getList: getProjectCateList,
  callback: () => changePage(1),
  loading,
};
const newList = computed(() => {
  return list.value.map((item) => {
    return {
      ...item,
      projectTypeName: ProjectType.find((type) => type.value === item.projectType)?.label,
      projectStatusName: item.projectStatus === "enable" ? "启用" : "停用",
    };
  });
});

const { cateList, current, getCateList, changeCurrent, componentProps, cateTree } = useClassifyList(options);
const { page, pageSize, changePage, changeSize } = useElPagination(getList);
async function getList() {
  if (current.value._id || current.value.$type === 'all') {
    const childrenIds = Array.isArray(current.value.childrenIds) ? current.value.childrenIds : [];
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      corpId: sessionStorage.getItem("corpId"),
      userId: sessionStorage.getItem("userId"),
      // cateIds: [current.value._id, ...childrenIds],
      projectName: projectName.value,
      showDepts: true
    }
    if (current.value.$type !== 'all') params.cateIds = [current.value._id, ...childrenIds];
    const { success, data, message } = await getProjectList(params);
    const { list: arr, total: count = 0 } = data;
    if (success) {
      list.value = arr.map(i => {
        const depts = Array.isArray(i.depts) ? i.depts : [];
        return { ...i, deptNames: depts.map(item => item.deptName).join(",") };
      });
      total.value = count;
    } else ElMessage.error(message);
  } else {
    list.value = [];
    total.value = 0;
  }
}

const project = ref({});
async function eidt(row) {
  project.value = row;
  show();
}

function addProject() {
  project.value = {};
  show();
}

function getAll() {
  current.value = { $type: 'all' }
}

async function changeStatus(row) {
  await ElMessageBox.confirm(`是否${row.projectStatus === "enable" ? "停用" : "启用"}该项目?`, "提示", { type: "warning" });
  const { success, message } = await updateProject({ id: row._id, params: { projectStatus: row.projectStatus === "enable" ? "disable" : "enable" } });
  if (success) {
    ElMessage.success(message);
    getList();
  } else {
    ElMessage.error(message);
  }
}

function setLabel(data, type) {
  if (data.level === 1 && type === 'edit') {
    return '编辑'
  }
}

function handleCate(data) {
  currentCate.value = { ...data };
  showCateModal()
}

async function onCateChange() {
  await getCateList();
  getList()
}
</script>
