<template>
  <div style="padding: 20px;">
    <div class="dept-layout">
      <!-- 左侧物料树 -->
      <n-card class="dept-tree-card" size="small">
        <template #header>
          <div class="dept-tree-header">
            <span>物料体系</span>
          </div>
        </template>
        <div class="dept-search">
          <n-input v-model:value="deptTreeSearch" placeholder="搜索物料" clearable size="small">
            <template #prefix>
              <n-icon>
                <SearchOutline/>
              </n-icon>
            </template>
          </n-input>
        </div>
        <div class="dept-tree-wrapper">
          <!--@drop="handleDrop"-->
          <n-tree
              :data="tableData"
              :pattern="deptTreeSearch"
              :default-expand-all="true"
              :selected-keys="selectedDeptKeys"
              :node-props="deptNodeProps"
              key-field="id"
              label-field="deptName"
              children-field="children"
              selectable
              block-line
              draggable
          />
        </div>
        <template #footer>
          <n-button 
           block 
           type="success"
           dashed 
           size="small"  
           @click="addfz"
          >
            <template #icon>
              <n-icon>
                <AddOutline/>
              </n-icon>
            </template>
            新建物料分组
          </n-button>
        </template>
      </n-card>

      <!-- 右侧用户列表 -->
      <n-card class="user-list-card" size="small">
        <template #header>
          <div class="card-header">
            <!--v-if="selectedDeptId && hasPermission('sys:dept:edit')"-->
            <n-button 
              type="success" 
              ghost
              size="small" 
              :render-icon="renderIcon" 
              @click="addwul"
            >
              新建物料
            </n-button>
            <!-- <span>{{ selectedDeptName ? `【${selectedDeptName}】部门成员` : '所有用户' }}</span>
            <n-space>
              <n-button v-if="selectedDeptId && hasPermission('sys:dept:edit')" size="small" @click="handleEditDept">
                编辑部门
              </n-button>
              <n-button v-if="selectedDeptId && hasPermission('sys:dept:add')" type="primary" size="small"
                        @click="handleAdd(selectedDeptId)">
                新增子部门
              </n-button>
              <n-button v-if="selectedDeptId && hasPermission('sys:dept:delete')" type="error" size="small"
                        @click="handleDeleteDept">
                删除部门
              </n-button>
            </n-space> -->
          </div>
        </template>

        <!-- 物料表格 -->
        <n-data-table
            :columns="userColumns"
             striped 
            :bordere="false"
            :single-line="false"
            :data="userData"
            :loading="userLoading"
            :row-key="(row: SysUser) => row.id"
            remote
        />

        <div style="display: flex; justify-content: flex-end; margin-top: 12px">
          <n-pagination
              v-model:page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :item-count="pagination.itemCount"
              :page-sizes="pagination.pageSizes"
              show-size-picker
              @update:page="handlePageChange"
              @update:page-size="handlePageSizeChange"
          />
        </div>
      </n-card>
    </div>

  <!--新建物料分组-->
  <n-modal 
     v-model:show="fenzupop" 
     title="新建物料分组" 
     preset="card" 
     style="width: 550px" 
     :mask-closable="false"
    >
    <n-form 
       ref="fenzRef" 
       :model="fenzformdata" 
       :rules="fzrules" 
       label-placement="left" 
       label-width="90">
        <n-form-item label="父分组" path="fid">
          <n-tree-select
              v-model:value="fenzformdata.fid"
              :options="deptOptions"
              key-field="id"
              label-field="deptName"
              children-field="children"
              placeholder="请选择父分组"
              clearable
              default-expand-all
          />
        </n-form-item>


        <n-form-item label="分组编号" path="num">
          <n-input v-model:value="fenzformdata.num" placeholder="请输入分组编号"/>
        </n-form-item>

        <n-form-item label="分组名称" path="name">
          <n-input v-model:value="fenzformdata.name" placeholder="请输入分组名称"/>
        </n-form-item>

        <n-form-item label="启用状态" path="state">
          <n-switch v-model:value="fenzformdata.state" :checked-value="1" :unchecked-value="0">
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="fenzupop = false">取消</n-button>
          <n-button type="success" :loading="submitLoading" @click="fzsave">确定</n-button>
        </n-space>
      </template>
    </n-modal>


    <!-- 物料新增编辑弹窗 -->
    <n-modal 
     v-model:show="wulipop" 
     :title="modalTitle" 
     preset="card" 
     style="width: 550px" 
     :mask-closable="false"
    >
      <n-form 
       ref="formRef" 
       :model="wlformdata" 
       :rules="xzwlrules" 
       label-placement="left" 
       label-width="90">
        <!-- <n-form-item label="上级部门" path="parentId">
          <n-tree-select
              v-model:value="formData.parentId"
              :options="deptOptions"
              key-field="id"
              label-field="deptName"
              children-field="children"
              placeholder="请选择上级部门"
              clearable
              default-expand-all
          />
        </n-form-item> -->


        <n-form-item label="物料编码" path="num">
          <n-input v-model:value="wlformdata.num" placeholder="请输入物料编码"/>
        </n-form-item>
        <n-form-item label="物料名称" path="name">
          <n-input v-model:value="wlformdata.name" placeholder="请输入物料名称"/>
        </n-form-item>
        <n-form-item label="重要程度" path="zycd">
          <n-input v-model:value="wlformdata.zycd" placeholder="请输入重要程度"/>
        </n-form-item>
        <n-form-item label="属性" path="shux">
          <n-input v-model:value="wlformdata.shux" placeholder="请选择属性"/>
        </n-form-item>
        <n-form-item label="单重" path="danz">
          <n-input v-model:value="wlformdata.danz" placeholder="请输入单重"/>
        </n-form-item>
        <n-form-item label="型号" path="xingh">
          <n-input v-model:value="wlformdata.xingh" placeholder="请输入型号"/>
        </n-form-item>
        <n-form-item label="材质" path="caiz">
          <n-space vertical style="width: 100%;">
            <n-select v-model:value="wlformdata.caiz" :options="[{label:'铝合金',value:1},{label:'不锈钢',value:2}]" />
          </n-space>
        </n-form-item>
        <n-form-item label="物料分类" path="wlfl">
          <n-space vertical style="width: 100%;">
            <n-select v-model:value="wlformdata.wlfl" :options="[{label:'铝合金',value:1},{label:'不锈钢',value:2}]" />
          </n-space>
        </n-form-item>
        <n-form-item label="类型" path="type">
          <n-input v-model:value="wlformdata.type" placeholder="请输入类型"/>
        </n-form-item>
        <n-form-item label="单位" path="danw">
          <n-space vertical style="width: 100%;">
            <n-select v-model:value="wlformdata.danw" :options="[{label:'铝合金',value:1},{label:'不锈钢',value:2}]" />
          </n-space>
        </n-form-item>
        <n-form-item label="状态" path="zhuangt">
          <n-switch v-model:value="wlformdata.zhuangt" :checked-value="1" :unchecked-value="0">
            <template #checked>正常</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="wulipop = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!--详情-->
    <n-modal
      v-model:show="showdetai"
      preset="card"
      title="物料详情"
      content-scrollable
      :style="{ width: '600px', height: '400px' }"
      :segmented="{ content: true, footer: true }"
    >
     <n-descriptions 
      label-placement="left" 
      :column="2"
      :content-style="{color:'#000'}"
      >
        <n-descriptions-item label="物料编号">
          1234567899
        </n-descriptions-item>
        <n-descriptions-item label="物料名称">
          双门双抽落地柜
        </n-descriptions-item>
        <n-descriptions-item label="物料分组">
          0001-报价
        </n-descriptions-item>
        <n-descriptions-item label="工艺路线">
          -
        </n-descriptions-item>
        <n-descriptions-item label="规格">
          50*500*100
        </n-descriptions-item>
        <n-descriptions-item label="基础单位">
          件
        </n-descriptions-item>
      </n-descriptions>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import {
  ref, 
  reactive, 
  h, 
  onMounted, 
  computed, 
  type HTMLAttributes
} from 'vue'

import {
  NButton,
  NIcon,
  NTag,
  NSpace,
  NPagination,
  useMessage,
  useDialog,
  
  type DataTableColumns,
  type FormInst,
  type FormRules,
  type TreeOption,
  type TreeDropInfo
} from 'naive-ui'
import {SearchOutline, AddOutline} from '@vicons/ionicons5'
import {deptApi, type SysDept} from '@/api/org'
import {userApi, type SysUser, postApi} from '@/api/system'
import {useUserStore} from '@/stores/user'

const message = useMessage()
const dialog = useDialog()
const userStore = useUserStore()
const hasPermission = (permission: string) => userStore.hasPermission(permission)

// ==================== 物料树逻辑 ====================
const deptTreeSearch = ref('')
const tableData = ref<SysDept[]>([]) // 树形数据

const selectedDeptKeys = ref<number[]>([])
const selectedDeptId = ref<number | undefined>(undefined)
const selectedDeptName = ref('')

const deptOptions = computed(() => [
  {id: 0, deptName: '主目录', children: tableData.value}
])

const deptNodeProps = ({option}: { option: TreeOption }): HTMLAttributes => {
  return {
    onClick() {
      const id = option.id as number
      if (selectedDeptId.value === id) {
        selectedDeptId.value = undefined
        selectedDeptKeys.value = []
        selectedDeptName.value = ''
      } else {
        selectedDeptId.value = id
        selectedDeptKeys.value = [id]
        selectedDeptName.value = option.deptName as string
      }
      handlePageChange(1)
    }
  }
}

async function loadData() {
  try {
    tableData.value = await deptApi.deptTree()
  } catch (error) {
    console.error('加载物料失败:', error)
  }
}

function renderIcon() {
  return h(NIcon, null, {
    default: () => h(AddOutline)
  })
}

//新增物料分组
let fenzupop = ref(false)
let fenzformdata = reactive<any>({
  fid:'',
  fzmun:'',
  fzname:'',
  beizhu:'',
  state:''
})

const fzrules = {
  num: [{required: true, message: '请输入分组编号', trigger: 'blur'}],
  name: [{required: true, message: '请输入分组名称', trigger: 'blur'}],
}

function addfz() {
  fenzupop.value = true
}

//提交保存
const fenzRef = ref()
 function fzsave() {
  fenzRef.value?.validate((v:any) => {
    if (!v) {
      message.success('操作成功')
    }
  })
}

//新增物料
let wulipop = ref(false)
let wlformdata = reactive<any>({
  num:'',       //物料编码
  name:'',      //物料名称
  zycd:'',      //重要程度
  shux:'',      //属性
  danz:'',      //单重
  xingh:'',     //型号
  caiz:'',      //材质
  wlfl:'',      //物料分类
  type:'',      //类型
  danw:'',       //单位
  zhuangt:1    //状态
})

const xzwlrules: FormRules = {
  num: [{required: true, message: '请输入物料编号', trigger: 'blur'}],
  name: [{required: true, message: '请输入物料名称', trigger: 'blur'}]
}

function addwul() {
  wulipop.value = true
}

//物料详情
 let showdetai = ref(false)
 

// async function handleDrop({node, dragNode, dropPosition}: TreeDropInfo) {
//   const dragId = dragNode.id as number
//   const targetId = node.id as number

//   let parentId: number
//   if (dropPosition === 'after') {
//     // 拖拽到目标节点内部，目标节点成为新的父节点
//     parentId = targetId
//   } else {
//     // 拖拽到目标节点的前后，目标节点的父节点成为新的父节点
//     parentId = (node.parentId as number) || 0
//   }

//   try {
//     await deptApi.move(dragId, parentId)
//     message.success('移动成功')
//     loadData() // 重新加载树形结构
//   } catch (error) {
//     // 错误已在请求拦截器处理
//   }
// }

// ==================== 物料列表逻辑 ====================
const userData = ref<SysUser[]>([])
const userLoading = ref(false)
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})


const userColumns: DataTableColumns<SysUser> = [
  {
    title: '物料编号', 
    key: 'id', 
    width: 100,
    align:'center',
    fixed: 'left',
    render(row:any){
      return h(
        'span',
        {
          style:{
            color:'#1161bf',
            borderBottom:'1px solid #1161bf',
            cursor:'pointer'
          },
          onClick:() => {
            showdetai.value = true
          }
        },
        row.id
      )
    }
  },
  {
    title: '物料名称', 
    key: 'username', 
    width: 100,
    align:'center'
  },
  {
    title: '附件', 
    key: 'nickname', 
    width: 100,
    align:'center'
  },
  {
    title: '物料分组', 
    key: 'deptName', 
    width: 120, 
    render(row) {
      return row.deptName || '-'
    },
    align:'center'
  },
  {
    title: '工艺路线', 
    key: 'postNames', 
    width: 150,
    align:'center'
  },
  {
    title: '物料来源类型',
    key: 'userType',
    width: 110,
    align:'center'
    // render(row) {
    //   const typeMap: Record<string, { type: 'info' | 'success' | 'warning'; label: string }> = {
    //     admin: {type: 'info', label: '后台管理员'},
    //     pc: {type: 'success', label: 'PC前台'},
    //     app: {type: 'warning', label: 'App/小程序'}
    //   }
    //   const t = typeMap[row.userType || 'admin'] || {type: 'info', label: row.userType || '未知'}
    //   return h(NTag, {type: t.type, size: 'small'}, {default: () => t.label})
    // }
  },
  {
    title: '规格', 
    key: 'phone', 
    width: 120,
    align:'center'
  },
  {
    title: '基础单位',
    key: 'isQuit',
    width: 100,
    align:'center'
  },
  {
    title: '批号管理',
    key: 'status',
    width: 100,
    align:'center'
  },
  {
    title: '属性管理', 
    key: 'createTime', 
    width: 170,
    align:'center'
  },
  {
    title: '品牌', 
    key: 'createTime', 
    width: 170,
    align:'center'
  },
  {
    title: '型号', 
    key: 'createTime', 
    width: 170,
    align:'center'
  },
  {
    title: '启用状态', 
    key: 'createTime', 
    width: 170,
    align:'center'
  },
  {
    title: '创建时间', 
    key: 'createTime', 
    width: 170,
    align:'center'
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align:'center',
    fixed: 'right',
    render(row) {
      const buttons:any = []
      if (hasPermission('sys:role:edit')) {
        buttons.push(
          h(
            NButton, 
            { size: 'small',ghost:true,type:'success', onClick: () => {
              addwul()
            } }, 
            { default: () => '编辑' }
          )
        )
      }
      if (hasPermission('sys:role:delete')) {
        buttons.push(
          h(
            NButton, 
            { size: 'small',ghost:true, type: 'error', onClick: () => {console.log(row)} }, 
            { default: () => '删除' }
          )
        )
      }
      return buttons.length > 0 ? h(NSpace, null, { default: () => buttons }) : '-'
    }
  }
]

async function loadUserData() {
  userLoading.value = true
  try {
    const res = await userApi.page({
      page: pagination.page,
      pageSize: pagination.pageSize,
      deptId: selectedDeptId.value
    })
    userData.value = res.list
    pagination.itemCount = Number(res.total)
  } catch (error) {
    console.error('加载用户数据失败:', error)
  } finally {
    userLoading.value = false
  }
}

function handlePageChange(page: number) {
  pagination.page = page
  loadUserData()
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize
  handlePageChange(1)
}




// ==================== 部门维护逻辑 ====================
const modalVisible = ref(false)
const modalTitle = ref('')
const formRef = ref<FormInst | null>(null)
const submitLoading = ref(false)
const formData = reactive<SysDept>({
  id: undefined,
  parentId: 0,
  deptName: '',
  sort: 0,
  leader: '',
  phone: '',
  email: '',
  status: 1
})
const rules: FormRules = {
  deptName: [{required: true, message: '请输入部门名称', trigger: 'blur'}]
}

function handleAdd(parentId: number = 0) {
  modalTitle.value = '新增部门'
  Object.assign(formData, {id: undefined, parentId, deptName: '', sort: 0, leader: '', phone: '', email: '', status: 1})
  modalVisible.value = true
}

async function handleEditDept() {
  if (!selectedDeptId.value) return
  try {
    const dept = await deptApi.detail(selectedDeptId.value)
    modalTitle.value = '编辑部门'
    Object.assign(formData, dept)
    modalVisible.value = true
  } catch (error) {
    console.error('获取部门详情失败:', error)
  }
}

function handleDeleteDept() {
  if (!selectedDeptId.value) return
  dialog.warning({
    title: '提示',
    content: `确定要删除部门"${selectedDeptName.value}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deptApi.delete(selectedDeptId.value!)
        message.success('删除成功')
        selectedDeptId.value = undefined
        selectedDeptKeys.value = []
        selectedDeptName.value = ''
        loadData()
        loadUserData()
      } catch (error) {
        console.error('删除部门失败:', error)
      }
    }
  })
}

function handleSubmit() {
  formRef.value?.validate((errors) => {
    if (!errors) {
         submitLoading.value = true
        if (formData.id) {
          deptApi.update(formData).then(() => {
            message.success('更新成功')
            modalVisible.value = false
            loadData()
          })
          
        } else {
          deptApi.create(formData).then(() => {
            message.success('创建成功')
            modalVisible.value = false
            loadData()
          })
          
        }
    }
  })
  // try {
  //   await formRef.value?.validate()
  //   submitLoading.value = true
  //   if (formData.id) {
  //     await deptApi.update(formData)
  //     message.success('更新成功')
  //   } else {
  //     await deptApi.create(formData)
  //     message.success('创建成功')
  //   }
  //   modalVisible.value = false
  //   loadData()
  // } catch (error) {
  //   console.error('提交失败:', error)
  // } finally {
  //   submitLoading.value = false
  // }
}

onMounted(() => {
  loadData()
  loadUserData()
})
</script>

<style scoped>
/* .page-container {
  height: calc(100vh - 40px);
} */
.dept-layout {
  display: flex;
  gap: 12px;
  height: 100%;
}

.dept-tree-card {
  width: 260px;
  flex-shrink: 0;
}

.dept-tree-header {
  font-weight: bold;
}

.dept-search {
  margin-bottom: 10px;
}

.dept-tree-wrapper {
  height: calc(100vh - 280px);
  overflow-y: auto;
}

.user-list-card {
  flex: 1;
  min-width: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
