<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="top"
      class="customer-form"
      :disabled="isDetailMode"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户组" prop="customerGroup">
            <el-select v-model="formData.customerGroup" placeholder="请选择客户组">
              <el-option
                v-for="option in customerGroupOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单类型" prop="orderType">
            <el-select v-model="formData.orderType" placeholder="请选择订单类型">
              <el-option
                v-for="option in orderTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 详情模式下的Tab页 -->
      <el-tabs v-if="isDetailMode" v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="倍数" name="multiple" />
        <el-tab-pane label="客户" name="customer" />
      </el-tabs>
      
      <!-- 明细表格 -->
      <div v-if="activeTab === 'multiple'">
        <div class="edit-table-header mb-3">
          <el-button
            v-if="!isDetailMode"
            type="primary"
            @click="handleAddRow"
            :disabled="isDetailMode"
          >
            新增
          </el-button>
        </div>
        <el-table
          v-if="formData.quantityDetailss.length > 0"
          :data="formData.quantityDetailss"
          border
          style="width: 100%"
          height="300px"
        >
          <!-- 序号列 -->
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          
          <!-- 数量(>)列 -->
          <el-table-column
            prop="minQuantity"
            label="数量(>)"
            align="center"
          >
            <template #default="{ row }">
              <div class="input-with-prefix">
                <span class="prefix">></span>
                <el-input-number
                v-model="row.minQuantity"
                :min="0"
                :step="1"
                :precision="0"
                :disabled="isDetailMode"
                style="width: 100%"
                @change="handleMinQuantityChange(row)"
              />
              </div>
            </template>
          </el-table-column>
          
          <!-- 数量(<=)列 -->
          <el-table-column
            prop="maxQuantity"
            label="数量(<=)"
            align="center"
          >
            <template #default="{ row }">
              <div class="input-with-prefix">
                <span class="prefix">&lt;=</span>
                <el-input-number
                v-model="row.maxQuantity"
                :min="0"
                :max="1000000"
                :step="1"
                :precision="0"
                :disabled="isDetailMode"
                style="width: 100%"
                @change="handleMaxQuantityChange(row)"
              />
              </div>
            </template>
          </el-table-column>
          
          <!-- 倍数列 -->
          <el-table-column
            prop="multiplier"
            label="倍数"
            align="center"
          >
            <template #default="{ row }">
              <el-input-number
                v-model="row.multiplier"
                :min="0"
                :step="0.1"
                :precision="2"
                :disabled="isDetailMode"
                style="width: 100%"
                @change="(value) => {
                  if (value !== null) {
                    // 移除末尾的0
                    row.multiplier = Number(value.toFixed(2))
                  }
                }"
              />
            </template>
          </el-table-column>
          
          <!-- 操作列 -->
          <el-table-column
            label="操作"
            width="100"
            align="center"
            v-if="!isDetailMode"
          >
            <template #default="{ $index }">
              <el-button
                type="danger"
                link
                @click="handleDeleteRow($index)"
                :disabled="formData.quantityDetailss.length <= 1"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="empty-table">
          <p>暂无明细数据，请点击上方按钮添加</p>
        </div>
      </div>
      
      <!-- 客户Tab页内容 -->
      <div v-if="isDetailMode && activeTab === 'customer'" class="customer-tab-content">
        <TableList ref="customerTableRef" :config="customerTableConfig" :is-popup="true" :no-padding="true"/>
      </div>
    </el-form>
    <template #footer v-if="!isDetailMode">
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          保存
        </el-button>
      </div>
    </template>

    <template #footer v-else>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import EditTable from '@/components/EditTable/index.vue'
import TableList from '@/components/TableList/index.vue'
import { FieldType } from '@/components/EditTable/types'
import { multipleSettingOperationLogPage } from '@/api/print/multipleSetting'
import { customerGroupPage } from '@/api/print/customerGroup'
// 明细表格数据类型
interface EditTableItem {
  id?: number
  minQuantity: number
  maxQuantity: number
  multiple: number
}

// 多设置表单数据类型
interface MultipleSettingFormData {
  id?: number
  customerGroup: string
  orderType: string
  quantityDetailss: EditTableItem[]
}

interface Props {
  visible: boolean
  mode: 'add' | 'edit' | 'detail'
  data?: MultipleSettingFormData
  customerGroupOptions?: Array<{ value: string; label: string }>
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': [type: 'save', data: MultipleSettingFormData]
}>()

// 表单引用
const formRef = ref()
const customerTableRef = ref()
// 弹窗可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})
const titleMap = {
  add: '新增',
  edit: '编辑',
  detail: '详情'
}
// 弹窗标题
const dialogTitle = ref('')

// 是否为详情模式
const isDetailMode = ref(false)

// 提交加载状态
const submitLoading = ref(false)

// Tab页状态
const activeTab = ref('multiple')

// 客户组选项
const customerGroupOptions = computed(() => props.customerGroupOptions || [])

// 客户表格配置
const customerTableConfig = computed(() => {
  return {
    table: {
      index: true,
      columns: [
        {
          prop: 'customerSapCode',
          label: '客户SAP编码',
          align: 'center'
        },
        {
          prop: 'customerName',
          label: '客户名称',
          align: 'center'
        }
      ]
    },
    pagination: {
      show: true,
      pageSize: 10
    },
    api: {
      getList: (params) => {
        return customerGroupPage({
          ...params,
          customerGroup: formData.customerGroup,
          sourceType: 2
        })
      }
    }
  }
})

// 订单类型选项
const orderTypeOptions = [
  { value: '0', label: 'B2B订单' },
  { value: '1', label: 'B2C订单' }
]

// 明细表格列配置
const editTableColumns = [
  {
    prop: 'minQuantity',
    label: '数量(>)',
    type: FieldType.NUMBER,
    min: 0,
    step: 1,
    precision: 0,
    required: true
  },
  {
    prop: 'maxQuantity',
    label: '数量(<=)',
    type: FieldType.NUMBER,
    min: 0,
    step: 1,
    precision: 0,
    required: true
  },
  {
    prop: 'multiple',
    label: '倍数',
    type: FieldType.NUMBER,
    min: 0,
    step: 0.1,
    precision: 2,
    required: true
  }
]

// 表单数据
const formData = reactive<MultipleSettingFormData>({
  id: undefined,
  customerGroup: '',
  orderType: '',
  quantityDetailss: [{
    minQuantity: 0,
    maxQuantity: 0,
    multiplier: 0
  }]
})
// 自定义校验规则：minQuantity必须小于maxQuantity
const validateMinMaxQuantity = (rule: any, value: any, callback: any) => {
  if (!value || !value.length) {
    callback()
    return
  }

  const invalidRow = value.find((row: any) => {
    return row.minQuantity >= row.maxQuantity
  })

  if (invalidRow) {
    callback(new Error('数量(>)必须小于数量(<=)'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules = {
  orderType: [{ required: true, message: '请选择订单类型', trigger: 'blur' }],
  quantityDetailss: [{ validator: validateMinMaxQuantity, trigger: 'change' }]
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    customerGroup: '',
    orderType: '',
    quantityDetailss: [{
      minQuantity: 0,
      maxQuantity: 0,
      multiplier: 0
    }]
  })
  formRef.value?.clearValidate()
}

// 初始化表单数据
const initFormData = () => {
  console.log('----模式----', props.mode)
  dialogTitle.value = titleMap[props.mode] || ''
  isDetailMode.value = props.mode === 'detail'
  resetForm()
  
  // 重置tab标签页的值
  activeTab.value = 'multiple'
  
  if (props.data) {
    Object.assign(formData, {
      ...props.data,
      quantityDetailss: props.data.quantityDetailss || [{
        minQuantity: 0,
        maxQuantity: 0,
        multiplier: 0
      }]
    })
  }
}
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  // 校验每个明细的minQuantity和maxQuantity不能为空
  const invalidRows = formData.quantityDetailss.filter(row => {
    return row.minQuantity === null || row.minQuantity === undefined || row.minQuantity === '' ||
           row.maxQuantity === null || row.maxQuantity === undefined || row.maxQuantity === ''
  })

  if (invalidRows.length > 0) {
    ElMessage.error('请填写所有明细的数量范围')
    return
  }

  try {
    await formRef.value.validate()
    submitLoading.value = true
    emit('success', 'save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  resetForm()
}

// 新增明细行
const handleAddRow = () => {
  formData.quantityDetailss.push({
    minQuantity: 0,
    maxQuantity: 0,
    multiplier: 0
  })
}

// 删除明细行
const handleDeleteRow = (index: number) => {
  if (formData.quantityDetailss.length > 1) {
    formData.quantityDetailss.splice(index, 1)
  }
}

// 处理minQuantity变化
const handleMinQuantityChange = (row: any) => {
  // 确保minQuantity小于maxQuantity
  if (row.minQuantity >= row.maxQuantity) {
    ElMessage.error('数量(>) 不能大于 数量(<=)')
    row.minQuantity = ''
  }
}

// 处理maxQuantity变化
const handleMaxQuantityChange = (row: any) => {
  // 确保maxQuantity大于minQuantity
  if (row.maxQuantity <= row.minQuantity) {
      ElMessage.error('数量(<=) 不能小于 数量(>)')
      row.maxQuantity = ''
  }
}
const handleTabChange = (tab: string) => {
  if (tab === 'customer') {
    nextTick(() => {
      customerTableRef.value?.getList()
    })
  }
}
// 监听弹窗显示变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initFormData()
  }
})
</script>

<style scoped>
.customer-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 8px 16px;
  font-weight: 500;
}

/* 明细表格样式 */
.edit-table-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.input-with-prefix {
  display: flex;
  align-items: center;
  width: 100%;
}

.prefix {
  margin-right: 8px;
  font-weight: 500;
}

.empty-table {
  padding: 40px 0;
  text-align: center;
  color: #999;
}

/* 调整输入框大小 */
:deep(.el-input-number) {
  width: 100px;
}

</style>