<template>
  <ElDialog
    v-model="visible"
    :title="isEdit ? '编辑配货区' : '新增配货区'"
    :close-on-click-modal="false"
    width="800px"
  >
    <el-form ref="formRef" label-width="170px" :model="form" :rules="rules">
      <el-form-item label="配货区说明" prop="areaDesc">
        <el-input
          v-model="form.areaDesc"
          style="width: 100%"
          clearable
          maxlength="100"
          show-word-limit
          :disabled="isDisabled"
          placeholder="请输入配货区说明"
        />
      </el-form-item>
      <el-form-item label="配货区" prop="areaCode">
        <el-select
          v-model="form.areaCode"
          :disabled="isDisabled"
          style="width: 200px"
          placeholder="请选择配货区"
        >
          <el-option
            v-for="item in areaList"
            :key="item.code"
            :label="item.desc"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配货规则" prop="conditions">
        <div class="picking-rules">
          <div class="header">
            <span class="mr-10">满足条件</span>
            <el-radio-group v-model="form.matchType" :disabled="isDisabled">
              <el-radio :value="1">满足以下所有条件</el-radio>
              <el-radio :value="2">满足以下任一条件</el-radio>
            </el-radio-group>
          </div>
          <div
            v-for="(item, index) in form.conditions"
            :key="index"
            class="content"
          >
            <el-select
              v-model="item.conditionType"
              style="width: 160px"
              :disabled="isDisabled"
              placeholder="请选择配货规则"
              @change="handleConditionTypeChange(item)"
            >
              <el-option
                v-for="rule in getAvailablePickingRules(index)"
                :key="rule.code"
                :label="rule.desc"
                :value="rule.code"
              />
            </el-select>

            <el-select
              v-model="item.operator"
              style="width: 160px"
              :disabled="isDisabled"
              placeholder="请选择关系"
            >
              <el-option
                v-for="operator in getAvailableOperators(item.conditionType)"
                :key="operator.code"
                :label="operator.desc"
                :value="operator.code"
              />
            </el-select>

            <template v-if="item.conditionType === 'order_platform'">
              <el-select
                v-model="item.conditionValue"
                class="platform-select"
                style="width: 160px"
                :disabled="isDisabled"
                placeholder="请选择平台"
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="1"
                clearable
                popper-class="customize-select-style"
              >
                <el-option
                  v-for="platform in platformList"
                  :key="platform.type"
                  :label="platform.type"
                  :value="platform.type"
                  style="width: 160px"
                >
                  <img
                    :src="`/images/icon/${platform.icon.split('/').pop()}`"
                    style="height: 20px; margin: 5px 10px 0 0"
                  />
                  <span :title="platform.type">{{ platform.type }}</span>
                </el-option>
              </el-select>
            </template>

            <template v-else>
              <el-input-number
                v-model="item.conditionValue"
                style="width: 160px"
                :min="1"
                :max="999"
                :disabled="isDisabled"
                placeholder="请输入数字"
              />
            </template>

            <el-button
              v-if="form.conditions.length < (pickingRuleList?.length ?? 0)"
              type="primary"
              class="rule-action-btn"
              :icon="Plus"
              size="small"
              circle
              :disabled="isDisabled"
              @click="addPickingRuleItem"
            />
            <el-button
              v-if="form.conditions.length > 1"
              color="#F56C6C"
              class="rule-action-btn"
              :icon="Minus"
              size="small"
              circle
              plain
              :disabled="isDisabled"
              @click="removePickingRuleItem(index)"
            />
          </div>
        </div>
      </el-form-item>

      <el-form-item label="自动打单" prop="autoPrint">
        <el-switch
          v-model="form.autoPrint"
          size="large"
          placeholder="请选择是否自动打单"
        />
      </el-form-item>
      <el-form-item>
        <span v-if="form.autoPrint" class="item-info">
          开启后，配货分拣订单配齐时，自动打单，打单后订单状态转为待发货。
        </span>
        <span v-else class="item-info">
          关闭后，配货分拣订单配齐后仍在待配货状态，经过配货打单后订单状态转为待发货。
        </span>
      </el-form-item>
      <el-form-item label="是否对接二次扫码设备" prop="secondScan">
        <el-select
          v-model="form.secondScan"
          style="width: 200px"
          placeholder="请选择是否对接二次扫码设备"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="序号" prop="sortNo">
        <el-input-number
          v-model="form.sortNo"
          :min="1"
          :max="999"
          style="width: 200px"
          step-strictly
          controls-position="right"
          :disabled="isDisabled"
          placeholder="请输入序号"
        />
      </el-form-item>
      <el-form-item>
        <span class="item-info">配货规则逻辑冲突时，优先执行更小的序号</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex flex-center">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import platformJson from '@/json/platform.json'
import type {
  OperatorList,
  SortingRuleCondition,
  SortingRuleDetail,
} from '@/types/api/order'
import {
  getAreaListApi,
  getConditionTypeListApi,
  getOperatorListApi,
  addAreaApi,
  editAreaApi,
} from '@/api/order'

// 配货规则条件
const pickingRuleList = ref<OperatorList[]>()

// 配货规则操作符
const operatorList = ref<OperatorList[]>()

const props = defineProps<{
  modelValue: boolean
  isEdit?: boolean
  editData?: SortingRuleDetail
  warehouseId: number
  warehouseName: string
  isDisabled?: boolean
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit'): void
}>()

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

const formRef = ref<FormInstance>()
const areaList = ref<OperatorList[]>([])
const form = ref<SortingRuleDetail>({
  areaDesc: '',
  areaCode: '',
  matchType: 1,
  conditions: [
    {
      conditionType: '',
      operator: '',
      conditionValue: undefined,
    },
  ],
  secondScan: false,
  sortNo: 1,
  autoPrint: false,
  warehouseId: 0,
  warehouseName: '',
  defaultFlag: false,
})

// 获取可用的配货规则条件 （剔除已选中的配货规则）
const getAvailablePickingRules = (currentIndex: number) => {
  const selectedFields = form.value.conditions
    .filter((_, index) => index !== currentIndex)
    .map((item) => item.conditionType)
  return pickingRuleList.value?.filter(
    (rule) => !selectedFields.includes(rule.code),
  )
}

// 根据配货规则类型获取可用的操作符
const getAvailableOperators = (conditionType: string) => {
  const list = operatorList.value ?? []
  if (conditionType === 'order_total_num') {
    return list.filter((operator) => operator.code !== 'in')
  } else if (conditionType === 'order_platform') {
    return list.filter((operator) => operator.code === 'in')
  }
  return list
}

// 配货规则条件改变
const handleConditionTypeChange = (item: SortingRuleCondition) => {
  // 平台 只能选 in属于
  if (item.conditionType === 'order_platform') {
    item.conditionValue = undefined
    item.operator = 'in'
  }
  // 订单总件数 清空字段
  else if (item.conditionType === 'order_total_num') {
    item.conditionValue = undefined
    item.operator = 'gt'
  }
}

// 配货规则
const createPickingRuleItem = (): SortingRuleCondition => ({
  conditionType: '',
  operator: '',
  conditionValue: undefined,
})

// 配货规则校验
const validateConditions = (
  _rule: unknown,
  _value: unknown,
  callback: (error?: Error) => void,
) => {
  const items = form.value.conditions
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    const isValueValid =
      item.conditionType === 'order_platform'
        ? Array.isArray(item.conditionValue) && item.conditionValue.length > 0
        : item.conditionValue !== null && item.conditionValue !== undefined
    if (!item.conditionType || !isValueValid || !item.operator) {
      callback(new Error('请完善配货规则'))
      return
    }
  }
  callback()
}

const rules = computed(() => {
  const base = {
    areaDesc: [
      { required: true, message: '请输入配货区说明', trigger: 'blur' },
    ],
    areaCode: [{ required: true, message: '请选择配货区', trigger: 'change' }],
    autoPrint: [
      { required: true, message: '请选择是否自动打单', trigger: 'change' },
    ],
    secondScan: [
      {
        required: true,
        message: '请选择是否对接二次扫码设备',
        trigger: 'change',
      },
    ],
    sortNo: [{ required: true, message: '请输入序号', trigger: 'blur' }],
  }
  if (form.value.areaCode === 'AREA_0') return base
  return {
    ...base,
    conditions: [
      { validator: validateConditions, trigger: 'blur' },
      { required: true, message: '请完善配货规则', trigger: 'change' },
    ],
  }
})

const platformList = platformJson

const formatConditionsForForm = (conditions: SortingRuleCondition[]) =>
  conditions.map((item) => ({
    ...item,
    conditionValue:
      typeof item.conditionValue === 'string'
        ? item.conditionValue.split(',').filter(Boolean)
        : item.conditionValue,
  }))

// 添加配货规则
const addPickingRuleItem = () => {
  form.value.conditions.push(createPickingRuleItem())
  formRef.value?.validateField('conditions')
}

// 删除配货规则
const removePickingRuleItem = (index: number) => {
  form.value.conditions.splice(index, 1)
  formRef.value?.validateField('conditions')
}

// 加载配货区列表
// 新增：剔除已选配货区
// 编辑：剔除已选配货区，但包含当前配货区
// 编辑配货区0：列表包含配货区0（def === true)
const loadAreaList = async () => {
  const res = await getAreaListApi(props.warehouseId)
  if (res.code !== 200) return
  areaList.value = res.data
  // 新增
  if (!props.isEdit) {
    areaList.value = areaList.value.filter((item) => item.used === false)
  }
  // 编辑配货区0
  else if (props.editData?.areaCode === 'AREA_0') {
    areaList.value = areaList.value.filter((item) => item.def === true)
  }
  // 编辑其他配货区
  else {
    areaList.value = areaList.value.filter(
      (item) => item.used === false || item.code === props.editData?.areaCode,
    )
  }
}

// 获取配货规则条件
const getConditionTypeList = async () => {
  const res = await getConditionTypeListApi()
  if (res.code !== 200) return
  pickingRuleList.value = res.data
}

// 获取配货规则操作符
const getOperatorList = async () => {
  const res = await getOperatorListApi()
  if (res.code !== 200) return
  operatorList.value = res.data
}

// 提交
const handleSubmit = async () => {
  form.value.warehouseId = props.warehouseId
  form.value.warehouseName = props.warehouseName
  if (props.editData?.areaCode !== 'AREA_0') {
    await formRef.value?.validate()
  }
  const submitData = {
    ...form.value,
    // 格式化配货规则
    conditions: form.value.conditions.map(
      (item): SortingRuleCondition => ({
        ...item,
        conditionValue: Array.isArray(item.conditionValue)
          ? item.conditionValue.join(',')
          : item.conditionValue,
      }),
    ),
  }

  const res = props.isEdit
    ? await editAreaApi(submitData)
    : await addAreaApi(submitData)

  if (res.code !== 200) return
  ElMessage.success(props.isEdit ? '编辑成功' : '新增成功')
  visible.value = false
  emit('submit')
}

onMounted(async () => {
  await Promise.all([loadAreaList(), getConditionTypeList(), getOperatorList()])
  if (props.editData) {
    form.value = {
      ...props.editData,
      conditions: formatConditionsForForm(props.editData.conditions),
    }
  }
})
</script>
<style scoped lang="scss">
.item-info {
  font-size: 12px;
  color: #666;
  line-height: 1;
  margin-top: -15px;
}

.picking-rules {
  background-color: #eee;
  border-radius: 3px;
  padding: 5px 15px;
  width: 100%;

  .header {
    font-size: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;

    :deep(.el-radio__label) {
      font-size: 12px;
    }
  }

  .content {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 8px;

    &:first-of-type {
      margin-top: 6px;
    }
  }

  .rule-action-btn {
    font-size: 16px;
  }

  .platform-select {
    :deep(.el-select__wrapper) {
      height: var(--el-component-size);
      min-height: var(--el-component-size);
      box-sizing: border-box;
    }

    :deep(.el-select__selection) {
      flex-wrap: nowrap;
      overflow: hidden;
    }

    :deep(.el-select__selected-item) {
      flex-shrink: 1;
      min-width: 0;
      overflow: hidden;
    }

    :deep(.el-tag) {
      max-width: 100%;

      .el-tag__content {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>
<style lang="scss">
.customize-select-style {
  .el-select-dropdown__list {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
