<template>
  <el-dialog
    v-model="visible"
    title="创建回收单"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="回收机构" prop="organizationId">
        <el-select
          v-model="formData.organizationId"
          placeholder="请选择回收机构"
          style="width: 100%"
          @change="handleOrgChange"
        >
          <el-option
            v-for="org in organizations"
            :key="org.id"
            :label="org.orgName"
            :value="org.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="回收资产" prop="assetIds">
        <el-button
          :icon="Plus"
          @click="handleSelectAssets"
        >
          选择资产
        </el-button>
        <span style="margin-left: 10px">已选 {{ formData.assetIds.length }} 项</span>
      </el-form-item>

      <el-form-item label="资产明细" v-if="selectedAssets.length > 0">
        <el-table :data="selectedAssets" border max-height="300">
          <el-table-column prop="assetCode" label="资产编码" width="150" />
          <el-table-column prop="assetName" label="资产名称" min-width="150" />
          <el-table-column prop="deviceType.typeName" label="设备类型" width="120" />
          <el-table-column prop="purchasePrice" label="采购价格" width="120">
            <template #default="{ row }">
              {{ row.purchasePrice ? `¥${row.purchasePrice.toFixed(2)}` : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                link
                type="danger"
                @click="handleRemoveAsset(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="回收原因" prop="reason">
        <el-input
          v-model="formData.reason"
          type="textarea"
          :rows="4"
          placeholder="请输入回收原因"
        />
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        提交
      </el-button>
    </template>
  </el-dialog>

  <!-- 资产选择对话框 -->
  <el-dialog
    v-model="assetSelectVisible"
    title="选择资产"
    width="1000px"
    append-to-body
  >
    <div class="filter-section">
      <el-input
        v-model="assetFilters.keyword"
        placeholder="搜索资产编码/名称"
        clearable
        style="width: 250px"
        @keyup.enter="handleSearchAssets"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearchAssets">搜索</el-button>
    </div>

    <el-table
      :data="availableAssets"
      v-loading="assetLoading"
      border
      max-height="400"
      @selection-change="handleAssetSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="assetCode" label="资产编码" width="150" />
      <el-table-column prop="assetName" label="资产名称" min-width="150" />
      <el-table-column prop="deviceType.typeName" label="设备类型" width="120" />
      <el-table-column prop="organization.orgName" label="所属机构" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getAssetStatusType(row.status)">
            {{ getAssetStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="assetPagination.page"
        v-model:page-size="assetPagination.pageSize"
        :total="assetPagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSearchAssets"
        @current-change="handleSearchAssets"
      />
    </div>

    <template #footer>
      <el-button @click="assetSelectVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirmAssetSelection">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { createRecovery, getAssetList, getOrganizationTree } from '@/api'
import { ASSET_STATUS } from '@/utils/constants'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const submitting = ref(false)
const organizations = ref<any[]>([])
const availableAssets = ref<any[]>([])
const assetLoading = ref(false)
const assetSelectVisible = ref(false)
const tempSelectedAssets = ref<any[]>([])

const formData = reactive({
  organizationId: undefined as number | undefined,
  assetIds: [] as number[],
  reason: '',
  remark: ''
})

const formRules: FormRules = {
  organizationId: [{ required: true, message: '请选择回收机构', trigger: 'change' }],
  assetIds: [{ required: true, message: '请选择回收资产', trigger: 'change' }],
  reason: [{ required: true, message: '请输入回收原因', trigger: 'blur' }]
}

const assetFilters = reactive({
  keyword: ''
})

const assetPagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const selectedAssets = computed(() => {
  return availableAssets.value.filter(asset => formData.assetIds.includes(asset.id))
})

// 获取机构列表
const fetchOrganizations = async () => {
  try {
    const tree = await getOrganizationTree()
    const flatten = (nodes: any[]) => {
      const result: any[] = []
      nodes.forEach(node => {
        result.push(node)
        if (node.children) {
          result.push(...flatten(node.children))
        }
      })
      return result
    }
    organizations.value = flatten(tree)
  } catch (error) {
    console.error('获取机构失败', error)
  }
}

// 机构变化
const handleOrgChange = () => {
  formData.assetIds = []
}

// 选择资产
const handleSelectAssets = () => {
  if (!formData.organizationId) {
    ElMessage.warning('请先选择回收机构')
    return
  }
  assetSelectVisible.value = true
  handleSearchAssets()
}

// 搜索资产
const handleSearchAssets = async () => {
  assetLoading.value = true
  try {
    const data = await getAssetList({
      page: assetPagination.page,
      page_size: assetPagination.pageSize,
      organization_id: formData.organizationId,
      status: 'in_use',
      keyword: assetFilters.keyword
    })
    availableAssets.value = data.items
    assetPagination.total = data.total
  } catch (error) {
    ElMessage.error('获取资产列表失败')
  } finally {
    assetLoading.value = false
  }
}

// 资产选择变化
const handleAssetSelectionChange = (selection: any[]) => {
  tempSelectedAssets.value = selection
}

// 确认资产选择
const handleConfirmAssetSelection = () => {
  formData.assetIds = tempSelectedAssets.value.map(item => item.id)
  assetSelectVisible.value = false
}

// 移除资产
const handleRemoveAsset = (asset: any) => {
  const index = formData.assetIds.indexOf(asset.id)
  if (index > -1) {
    formData.assetIds.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await createRecovery(formData)
        ElMessage.success('创建成功')
        handleClose()
        emit('success')
      } catch (error) {
        ElMessage.error('创建失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  formData.assetIds = []
  visible.value = false
}

// 资产状态标签类型
const getAssetStatusType = (status: string) => {
  const item = Object.values(ASSET_STATUS).find(item => item.value === status)
  return item?.type || ''
}

// 资产状态名称
const getAssetStatusName = (status: string) => {
  const item = Object.values(ASSET_STATUS).find(item => item.value === status)
  return item?.label || status
}

watch(() => props.modelValue, (val) => {
  if (val) {
    fetchOrganizations()
  }
})
</script>

<style scoped lang="scss">
.filter-section {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
