<template>
  <div class="page-container">
    <n-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <n-form inline :model="searchForm" label-placement="left">
          <n-form-item label="工序名称">
            <n-input v-model:value="searchForm.name" placeholder="请输入工序名称" clearable />
          </n-form-item>
          <n-form-item>
            <n-space>
              <n-button type="primary" @click="handleSearch">
                <template #icon><n-icon><SearchOutline /></n-icon></template>
                搜索
              </n-button>
              <n-button @click="handleReset">
                <template #icon><n-icon><RefreshOutline /></n-icon></template>
                重置
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </div>

      <!-- 工具栏 -->
      <div class="table-toolbar">
        <n-space>
          <n-button @click="importModalVisible = true">
            <template #icon><n-icon><CloudUploadOutline /></n-icon></template>
            导入
          </n-button>
          <n-button @click="handleExport">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            导出{{ selectedIds.length > 0 ? `(${selectedIds.length})` : '' }}
          </n-button>
          <!-- <n-button type="error" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <template #icon><n-icon><TrashOutline /></n-icon></template>
            删除
          </n-button> -->
        </n-space>
      </div>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :row-key="(row) => row.id"
        :scroll-x="1200"
        v-model:checked-row-keys="selectedIds"
      />

      <div class="pagination-container" 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="[10, 20, 50, 100]"
                show-size-picker
                show-quick-jumper
                @update:page="handlePageChange"
                @update:page-size="handlePageSizeChange"
                @update:checked-row-keys="handleCheck"
              >
                <template #prefix>
                  共 {{ pagination.itemCount }} 条
                </template>
              </n-pagination>
            </div>

    </n-card>

    <!-- 编辑弹窗 -->
    <n-modal v-model:show="modalVisible" preset="card" :title="modalTitle" style="width: 600px">
      <n-form ref="formRef" :model="formData" :rules="formRules" label-placement="left" label-width="100px">
        <n-form-item label="工序名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入工序名称" />
        </n-form-item>
        <n-form-item label="工序编码" path="code">
          <n-input v-model:value="formData.code" placeholder="请输入工序编码" />
        </n-form-item>
        <n-form-item label="工序顺序" path="sort">
          <n-input v-model:value="formData.sort" placeholder="请输入工序顺序" />
        </n-form-item>
          <n-grid x-gap="12" :cols="2">
              <n-gi>
                   <n-form-item label="是否采购" path="procurement">
                    <n-radio-group v-model:value="formData.procurement" name="procurement">
                            <n-space>
                              <n-radio :value="1">是</n-radio>
                              <n-radio :value="0">否</n-radio>
                            </n-space>
                      </n-radio-group>
                  </n-form-item>
              </n-gi>
              <n-gi>
                  <n-form-item label="是否委外" path="outsource">
                      <n-radio-group v-model:value="formData.outsource" name="outsource">
                            <n-space>
                              <n-radio :value="1">是</n-radio>
                              <n-radio :value="0">否</n-radio>
                            </n-space>
                      </n-radio-group>
                  </n-form-item>
              </n-gi>
          </n-grid>
       
        <n-grid x-gap="12" :cols="2">
           <n-gi>
                <n-form-item label="是否质检" path="qualityInspection">
                  <n-radio-group v-model:value="formData.qualityInspection" name="qualityInspection">
                        <n-space>
                          <n-radio :value="1">是</n-radio>
                          <n-radio :value="0">否</n-radio>
                        </n-space>
                  </n-radio-group>
              </n-form-item>
           </n-gi>
           <n-gi>
                <n-form-item label="是否直接入库" path="storageEntry">
                    <n-radio-group v-model:value="formData.storageEntry" name="storageEntry">
                          <n-space>
                            <n-radio :value="1">是</n-radio>
                            <n-radio :value="0">否</n-radio>
                          </n-space>
                    </n-radio-group>
                </n-form-item>
           </n-gi>
        </n-grid>
        <n-form-item label="工作中心" path="workCenterName">
          <n-input v-model:value="formData.workCenterName" placeholder="请输入工作中心" />
        </n-form-item>
        <n-form-item label="生产车间" path="departmentName">
          <n-input v-model:value="formData.departmentName" placeholder="请输入生产车间(工序级)" />
        </n-form-item>
        <n-form-item label="工序说明" path="operDescription">
          <n-input v-model:value="formData.operDescription" type="textarea" placeholder="请输入工序说明" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 导入弹窗 -->
    <n-modal v-model:show="importModalVisible" preset="card" title="导入基础主数据--工序表" style="width: 500px">
      <n-space vertical>
        <n-alert type="info">
          <template #header>导入说明</template>
          <ul style="margin: 0; padding-left: 16px; line-height: 1.8">
            <li>请先下载导入模板，按模板格式填写数据</li>
            <li>支持 .xlsx 或 .xls 格式</li>
          </ul>
        </n-alert>
        <n-space>
          <n-button type="primary" @click="handleDownloadTemplate">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            下载模板
          </n-button>
        </n-space>
        <n-upload :max="1" accept=".xlsx,.xls" :show-file-list="true" :custom-request="handleImportUpload">
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <n-icon size="48" :depth="3"><CloudUploadOutline /></n-icon>
            </div>
            <n-text style="font-size: 16px">点击或拖拽文件到此处上传</n-text>
            <n-p depth="3" style="margin: 8px 0 0 0">支持 .xlsx 或 .xls 格式</n-p>
          </n-upload-dragger>
        </n-upload>
      </n-space>
      <template #footer>
        <n-button @click="importModalVisible = false">关闭</n-button>
      </template>
    </n-modal>

    <!--关联质检项抽屉-->
    <n-drawer v-model:show="qualityItemModel" :width="800" >
       <n-drawer-content title="质检项列表">
          <n-space justify="space-between" class="mb-3">
            <n-checkbox v-model:checked="isAllCheck" @update:checked="handleAllCheck">
              全选当前筛选工序
            </n-checkbox>
            <n-tag type="info">已勾选 {{ selectQualityItemIds.length }} 道质检项</n-tag>
          </n-space>

          <n-data-table
              :columns="qualityItemColums"
              :data="qualityItemList"
              :row-key="getRowKey"
              max-height="700"
              v-model:checked-row-keys="selectQualityItemIds"
              :scroll-x="1200"
              :loading="relateLoading"
              @update:checked-row-keys="onCheckedChange"
            />
            <div class="pagination-container" style="display: flex; justify-content: flex-end; margin-top: 12px">
              <n-pagination
                v-model:page="relatePagination.page"
                v-model:page-size="relatePagination.pageSize"
                :item-count="relatePagination.itemCount"
                :page-sizes="[10, 20, 50, 100]"
                show-size-picker
                show-quick-jumper
                @update:page="handleRelatePageChange"
                @update:page-size="handleRelatePageSizeChange"
              >
                <template #prefix>
                  共 {{ relatePagination.itemCount }} 条
                </template>
              </n-pagination>
            </div>
                  <!-- 底部操作按钮 -->
            <template #footer>
              <n-space justify="end">
                <n-button @click="qualityItemModel = false">取消</n-button>
              </n-space>
            </template>  
       </n-drawer-content>
    </n-drawer>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted,computed } from 'vue'
import { NButton, NSpace, NIcon, NUpload, useMessage, useDialog, type DataTableColumns, type UploadCustomRequestOptions, NTag } from 'naive-ui'
import { SearchOutline, RefreshOutline, AddOutline, TrashOutline, CreateOutline, CloudUploadOutline, DownloadOutline } from '@vicons/ionicons5'
import { basicProcessPlanApi, type BasicProcessPlan } from '@/api/basicProcessPlan'
import { qcItemApi,QcItem } from '@/api/qcItem'
import {qcitemProcessApi,QcitemProcess} from '@/api/qcitemProcess'

const message = useMessage()
const dialog = useDialog()

//关联质检项
const qualityItemModel = ref<boolean>(false)
const selectQualityItemIds = ref<number[]>([])
const qualityItemList = ref<QcItem[]>([])
const qualityItemRelate = ref<QcitemProcess>({
      processId: undefined,
      qualityItemIds: undefined
})
const relateLoading = ref<boolean>(false)
const relatePagination  = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})


// 搜索表单
const searchForm = reactive({
  id:  null as number | null,
  name: '',
})

// 表格数据
const tableData = ref<BasicProcessPlan[]>([])
const loading = ref(false)
const selectedIds = ref<number[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

// 弹窗
const modalVisible = ref(false)
const modalTitle = ref('')
const importModalVisible = ref(false)
const formRef = ref()
const defaultFormData: BasicProcessPlan = {
  name: '',
  code: '',
  sort: undefined,
  procurement: undefined,
  outsource: undefined,
  qualityInspection: undefined,
  storageEntry: undefined,
  workCenterName: '',
  departmentName: '',
  operDescription: '',
  status:undefined
}
const formData = reactive<BasicProcessPlan>({ ...defaultFormData })

// 字典选项（下拉框/单选框/复选框关联字典时使用）

// 表单校验规则
const formRules = {
}

// 表格列
const columns: DataTableColumns<BasicProcessPlan> = [
  { type: 'selection' },
  { title: '工序名称', key: 'name' },
  { title: '工序编码', key: 'code' },
  { title: '是否采购', key: 'procurement',
    render(row) {
      var opt = row.procurement
      return h(NTag,{type: opt ? 'success' : 'error', size: 'small'},{default: () => (opt ? '是' : '否')})  
    }
   },
  { title: '是否委外', key: 'outsource',
    render(row) {
      var opt = row.outsource
      return h(NTag,{type: opt ? 'success' : 'error', size: 'small'},{default: () => (opt ? '是' : '否')})  
    }
   },
  { title: '是否质检', key: 'qualityInspection',
    render(row) {
      var opt = row.qualityInspection
      return h(NTag,{type: opt ? 'success' : 'error', size: 'small'},{default: () => (opt ? '是' : '否')})  
    }
   },
  { title: '是否直接入库', key: 'storageEntry',
     render(row) {
      var opt = row.qualityInspection
      return h(NTag,{type: opt ? 'success' : 'error', size: 'small'},{default: () => (opt ? '是' : '否')})  
    }
   },
  { title: '工作中心', key: 'workCenterName' },
  { title: '生产车间', key: 'departmentName' },
  { title: '工序说明', key: 'operDescription' },
  { title: '状态', key: 'status',
      render(row){
       if(row.status == 0){
        return h(NTag, {
            type:'error', 
            size: 'small'
          }, 
          {
            default: () => '禁用'
          }
        )
      }
      if(row.status == 1){
        return h(NTag, {
            type:'success', 
            size: 'small'
          }, 
          {
            default: () => '启用'
          }
        )
      }
    }
   },
  { title: '创建人', key: 'createBy' },
  { title: '创建时间', key: 'createTime', width: 180 },
  {
    title: '操作',
    key: 'actions',
    width: 140,
    fixed: 'right',
    render(row) {
      return h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'nowrap' } }, [
        h(NButton, { size: 'small', quaternary: true, onClick: () => handleEdit(row) }, {
          default: () => [h(NIcon, null, { default: () => h(CreateOutline) }), ' 编辑']
        }),
        // h(NButton, { size: 'small', quaternary: true, type: 'error', onClick: () => handleDelete(row) }, {
        //   default: () => [h(NIcon, null, { default: () => h(TrashOutline) }), ' 删除']
        // }),
        h(NButton, { size: 'small', quaternary: true,  onClick: () => handleOpenRelateModel(row) }, {
          default: () => ['关联质检项']
        })
      ])
    }
  }
]

// 加载数据
async function loadData() {
  loading.value = true
  try {
    const res = await basicProcessPlanApi.page({
      page: pagination.page,
      pageSize: pagination.pageSize,
      id: searchForm.id || undefined,
      name: searchForm.name || undefined,
    })
    tableData.value = res.list
    pagination.itemCount = res.total
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1
  loadData()
}

// 重置
function handleReset() {
  searchForm.id =  null

  searchForm.name = ''

  handleSearch()
}

// 分页
function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

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

// 选择
function handleCheck(keys: Array<string | number>) {
  selectedIds.value = keys as number[]
}

// 新增
function handleAdd() {
  modalTitle.value = '新增基础主数据--工序表'
  Object.assign(formData, defaultFormData)
  modalVisible.value = true
}

// 编辑
function handleEdit(row: BasicProcessPlan) {
  modalTitle.value = '编辑基础主数据--工序表'
  Object.assign(formData, row)
  if (formData.createTime && typeof formData.createTime === 'string') {
    formData.createTime = new Date(formData.createTime.replace(' ', 'T')).getTime()
  }
  modalVisible.value = true
}

// 提交
async function handleSubmit() {
  await formRef.value?.validate()
  try {
    const submitData = { ...formData } as BasicProcessPlan
    if (typeof submitData.createTime === 'number') {
      submitData.createTime = new Date(submitData.createTime).toISOString().slice(0, 19).replace('T', ' ')
    }
    if (submitData.id) {
      await basicProcessPlanApi.update(submitData)
      message.success('修改成功')
    } else {
      await basicProcessPlanApi.create(submitData)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 删除
function handleDelete(row: BasicProcessPlan) {
  dialog.warning({
    title: '提示',
    content: '确定要删除该记录吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await basicProcessPlanApi.delete([row.id!])
        message.success('删除成功')
        loadData()
      } catch (error) {
        // 错误已在拦截器处理
      }
    }
  })
}

// 批量删除
function handleBatchDelete() {
  dialog.warning({
    title: '提示',
    content: `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await basicProcessPlanApi.delete(selectedIds.value)
        message.success('删除成功')
        selectedIds.value = []
        loadData()
      } catch (error) {
        // 错误已在拦截器处理
      }
    }
  })
}

// 导出
async function handleExport() {
  try {
    const params: Record<string, any> = {}
    if (selectedIds.value.length > 0) params.ids = selectedIds.value
    if (searchForm.id != null) params.id = searchForm.id
    if (searchForm.name) params.name = searchForm.name
    const blob = await basicProcessPlanApi.export(params)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '基础主数据--工序表数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 下载导入模板
async function handleDownloadTemplate() {
  try {
    const blob = await basicProcessPlanApi.downloadTemplate()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '基础主数据--工序表导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 导入上传
async function handleImportUpload({ file }: UploadCustomRequestOptions) {
  if (!file.file) return
  try {
    const result = await basicProcessPlanApi.importData(file.file)
    if (result.fail > 0) {
      dialog.warning({
        title: '导入结果',
        content: `成功: ${result.success} 条，失败: ${result.fail} 条\n错误信息: ${(result.errors || []).join('\n') || '无'}`,
        positiveText: '确定'
      })
    } else {
      message.success(`导入成功，共 ${result.success} 条数据`)
      importModalVisible.value = false
    }
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 加载字典选项
async function loadDictOptions() {
}

//开启关联质检项抽屉
function handleOpenRelateModel(row) {
    relatePagination.page = 1
    relatePagination.pageSize = 10
    relateLoading.value = true
    qualityItemModel.value = true
    qualityItemRelate.processId  = row.id
    getQualityList(row.id)
}

async function getQualityList(id) {
  
  try{
      const res = await qcItemApi.list({
                  id:id,
                  page:relatePagination.page,
                  pageSize:relatePagination.pageSize
      })

      qualityItemList.value = res.data.list
      relatePagination.itemCount = res.data.total

      //回显
      selectQualityItemIds.value = qualityItemList.value.filter(item=> item.isBind).map(item=>item.id)
      relateLoading.value = false
  }catch(error) {
      console.log("异常信息:"+error);
      message.error("获取质检列表失败")
      relateLoading.value = false
      
  }


}


//取消/全选
const isAllCheck = computed({
  get() {
    return qualityItemList.value.length > 0 && selectQualityItemIds.value.length === qualityItemList.value.length
  },
  set(val) {
    if(val) {
      selectQualityItemIds.value = qualityItemList.value.map(item=> item.id)
    }else{
      selectQualityItemIds.value = []
    }
    loadQualityItemCreateApi()
  }
})

const handleAllCheck = (val:boolean) => {
  isAllCheck.value = val
}

const onCheckedChange = async (keys:number[]) =>{
  selectQualityItemIds.value = keys
 
  loadQualityItemCreateApi()
}


const loadQualityItemCreateApi = async()=> {
    qualityItemRelate.qualityItemIds = selectQualityItemIds.value
    qualityItemRelate.page = relatePagination.page
    qualityItemRelate.pageSize = relatePagination.pageSize
    try{
      await qcitemProcessApi.qualityItemcreate(qualityItemRelate);
        message.success("关联成功")
        getQualityList(qualityItemRelate.processId)
      
    }catch(error) {
      message.error("关联失败")
    }
}

const getRowKey =  (row: any) => row.id
const qualityItemColums:  DataTableColumns<QcItem> = [
  { type: 'selection' },
  { title:"质检项名称", key:"name"},
  { title: "关联状态",key:"isBind",
     render(row) {
      const val = row.isBind;
      if (val) {
        return h(NTag, { type: "success" }, { default: () => "已关联" });
      } else {
        return h(NTag, { type: "default" }, { default: () => "未关联" });
      }
    }
  }
]

// 分页
function handleRelatePageChange(page: number) {
  relatePagination.page = page
  getQualityList(qualityItemRelate.processId)
 
}

function handleRelatePageSizeChange(pageSize: number) {
  relatePagination.pageSize = pageSize
  relatePagination.page = 1
  getQualityList(qualityItemRelate.processId)
 
}


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

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}
</style>