<template>
  <div class="app-container">
    <!-- 左侧岗位树 -->
    <ContentWrap class="left">
      <WorkstationTree @node-click="handleDeptNodeClick" />
    </ContentWrap>

    <!-- 右侧内容区 -->
    <ContentWrap class="right">
      <el-radio-group v-model="tabPosition" class="mb-30px">
        <el-radio-button label="craft">工艺</el-radio-button>
        <el-radio-button label="device">设备</el-radio-button>
      </el-radio-group>

      <div v-if="tabPosition === 'craft' || tabPosition === 'device'">
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item :label="tabPosition === 'craft' ? '工艺名称' : '设备名称'" prop="machineryName">
            <el-input
              v-model="queryParams.machineryName"
              :placeholder="tabPosition === 'craft' ? '请输入工艺名称' : '请输入设备名称'"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create',null,tabPosition)"
              v-hasPermi="['iscs:machinery:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="danger"
              plain
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['iscs:machinery:delete']"
            >
              <Icon icon="ep:delete" class="mr-5px" /> 批量删除
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 列表 -->
        <el-table
          v-loading="loading"
          :data="list"
          row-key="machineryId"
          :default-expand-all="isExpandAll"
          v-if="refreshTable"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="id"
            :label="tabPosition === 'craft' ? '工艺编号' : '设备编号'"
            width="130"
          />
          <el-table-column
            prop="machineryName"
            :label="tabPosition === 'craft' ? '工艺名称' : '设备名称'"
            width="260"
          />
          <el-table-column prop="workstationName" label="岗位" width="260" />
          <el-table-column
            prop="machineryImg"
            :label="tabPosition === 'craft' ? '工艺图' : '设备图'"
            width="260"
          >
            <template #default="scope">
              <UploadImg v-model="scope.row.machineryImg" :limit="1" height="75px" width="75px" />
            </template>
          </el-table-column>
          <el-table-column
            label="详情"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                v-throttle
                @click="handleLook(scope.row)"
              >
                <Icon icon="ep:view" class="mr-5px" /> 查看
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="260">
            <template #default="scope">

              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id,tabPosition)"
                v-hasPermi="['iscs:machinery:update']"
              >
                <Icon icon="ep:edit" class="mr-5px" /> 修改
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['iscs:machinery:delete']"
              >
                <Icon icon="ep:delete" class="mr-5px" /> 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </ContentWrap>

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

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { handleTree } from '@/utils/tree'
import * as TechnologyApi from '@/api/dv/technology'
import * as MarsDeptApi from '@/api/system/marsdept'
import * as LotoApi from '@/api/dv/lotoStation'
import TechnologyForm from './TechnologyForm.vue'
import WorkstationTree from './WordstationTree.vue'

defineOptions({ name: 'Technology' })

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

// 数据定义
const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const total = ref(0) // 总条数
const tabPosition = ref('craft') // 当前选中的标签页
const multiple = ref(true) // 是否多选
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const treeDataRef = ref() // 树形组件引用
const workstationOptions = ref([]) // 岗位树选项

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  machineryName: undefined,
  machineryCode: undefined,
  machineryType: undefined,
  workstationName: undefined,
  workstationId: undefined
})

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 监听标签页变化
watch(() => tabPosition.value, (newVal) => {
  if (newVal) {
    getList()
  }
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const type = tabPosition.value === 'craft' ? '工艺' : '设备'
    queryParams.machineryType = type
    const data = await TechnologyApi.listTechnology(queryParams)
    list.value = handleTree(data.list,'id','parentId')
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 岗位树节点点击事件 */
const handleDeptNodeClick = (data: any) => {
  if (data) {
    queryParams.workstationId = data.id
    queryParams.workstationName = data.workstationName
  } else {
    queryParams.workstationId = undefined
    queryParams.workstationName = undefined
  }
  getList()
}

/** 获取其他数据 */
const getOtherList = async () => {
  const data = { pageNo: 1, pageSize: -1 }
  try {
    const [lotoResponse, marsResponse] = await Promise.all([
      LotoApi.listLoto(data),
      MarsDeptApi.listMarsDept(data)
    ])
    workstationOptions.value = handleTree(marsResponse.list,'id','parentId')
    console.log(workstationOptions.value,'aaa')
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}
const queryFormRef=ref()
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number,tabPosition:string) => {
  formRef.value.open(type, id,tabPosition)
}
const ids = ref<number[]>([]) // 选中的数据
/** 删除按钮操作 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}
const handleDelete = async (id: number) => {
  const Ids = id || ids.value
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TechnologyApi.delTechnology(Ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}


/** 查看详情 */
const handleLook = (row: any) => {
  if (tabPosition.value === 'craft') {
    router.push(`/dv/technology/technologyDetail/CraftDetail?machineryId=${row.id}`)
  } else {
    router.push(`/dv/technology/technologyDetail/DeviceDetail?machineryId=${row.id}`)
  }
}

/** 初始化 **/
onMounted(async () => {
  await getOtherList()
  await getList()

})
</script>

<style scoped lang="scss">
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
}

.left {
  width: 15%;
  height: 100%;
  margin-right: 10px;
}

.deptTree {
  width: 100%;
  height: 90%;
}

.right {
  width: 83%;
  height: 100%;
}
</style>
