<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      min-label-width="68px"
    >
    <el-form-item :label="t('FactoryModeling.FactoryStructure.searchCodeLabel')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('FactoryModeling.FactoryStructure.searchCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('FactoryModeling.FactoryStructure.searchParentLabel')" prop="parentId">
        <el-tree-select
          v-model="queryParams.parentId"
          :data="organizationTree"
          :props="defaultProps"
          check-strictly
          @select="handleQuery"
          clearable
          default-expand-all
          :placeholder="t('FactoryModeling.FactoryStructure.searchParentPlaceholder')"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('FactoryModeling.FactoryStructure.searchNameLabel')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('FactoryModeling.FactoryStructure.searchNamePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="组织状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择组织状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MES_ORG_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item :label="t('FactoryModeling.FactoryStructure.searchOrgClassLabel')" prop="orgClass">
        <el-select
          v-model="queryParams.orgClass"
          :placeholder="t('FactoryModeling.FactoryStructure.searchOrgClassPlaceholder')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MES_ORG_CLASS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('FactoryModeling.FactoryStructure.searchButtonText') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('FactoryModeling.FactoryStructure.resetButtonText') }}</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['mes:organization:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('FactoryModeling.FactoryStructure.addButtonText') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:organization:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ t('FactoryModeling.FactoryStructure.exportButtonText') }}
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> {{ t('FactoryModeling.FactoryStructure.expandButtonText') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <!-- <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="所有" name="" />
      <el-tab-pane label="制浆" name="zhijiang" />
      <el-tab-pane label="成型" name="chengxing" />
      <el-tab-pane label="烘干" name="honggan" />
      <el-tab-pane label="转移" name="zhuanyi" />
      <el-tab-pane label="加湿" name="jiashi" />
      <el-tab-pane label="热压" name="reya" />
      <el-tab-pane label="切边" name="qiebian" />
      <el-tab-pane label="品检" name="pinjian" />
      <el-tab-pane label="打包" name="dabao" />
      <el-tab-pane label="贴标" name="tiebiao" />
      <el-tab-pane label="品印" name="pinyin" />
      <el-tab-pane label="塑封" name="sufeng" />
    </el-tabs> -->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableCodeColumn')" align="center" prop="code" />
      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableNameColumn')" align="center" prop="name" />

      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableSortColumn')" align="center" prop="sort" />
<!--      <el-table-column label="负责人" align="center" prop="workerUserId" />-->
      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableMachineColumn')" align="center" prop="machineName" />
      <!-- <el-table-column label="组织状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_ORG_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableOrgClassColumn')" align="center" prop="orgClass">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_ORG_CLASS" :value="scope.row.orgClass" />
        </template>
      </el-table-column>
      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableOrgTypeColumn')" align="center" prop="orgType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_ORG_TYPE" :value="scope.row.orgType" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('FactoryModeling.FactoryStructure.tableCreateTimeColumn')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column :label="t('FactoryModeling.FactoryStructure.tableOperateColumn')" align="center" fixed="right" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:organization:update']"
          >
            {{ t('FactoryModeling.FactoryStructure.tableEditAction') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['mes:organization:delete']"
          >
            {{ t('FactoryModeling.FactoryStructure.tableDeleteAction') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrganizationForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import {getIntDictOptions, getBoolDictOptions, DICT_TYPE, getStrDictOptions} from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import {defaultProps, handleTree} from '@/utils/tree'
import download from '@/utils/download'
import { OrganizationApi, OrganizationVO } from '@/api/mes/organization'
import OrganizationForm from './OrganizationForm.vue'

/** 产线工位 列表 */
defineOptions({ name: 'Organization' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<OrganizationVO[]>([]) // 列表的数据
const queryParams = reactive({
  code: undefined,
  name: undefined,
  parentId: undefined,
  sort: undefined,
  workerUserId: undefined,
  machineId: undefined,
  phone: undefined,
  email: undefined,
  isEnable: undefined,
  status: undefined,
  orgClass: undefined,
  orgType: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrganizationApi.getOrganizationList(queryParams)
    list.value = handleTree(data, 'id', 'parentId')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrganizationApi.deleteOrganization(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrganizationApi.exportOrganization(queryParams)
    download.excel(data, '产线工位.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 展开/折叠操作 */
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const toggleExpandAll = async () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  await nextTick()
  refreshTable.value = true
}
const organizationTree = ref() // 树形结构

/** 初始化 **/
onMounted(async () => {
  await getList()
  /** 获得产线工位树 */
  organizationTree.value = []
  const data = await OrganizationApi.getOrganizationList()
  const root: Tree = { id: 0, name: '顶级组织', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  organizationTree.value.push(root)
})
/** tab 切换 */
let activeName = ''
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.orgType = tab.paneName
  handleQuery()
}

</script>
