<template>
  <ElDialog
    v-model="visible"
    :title="isEdit ? '编辑分拣口' : '新增分拣口'"
    :close-on-click-modal="false"
    width="800px"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="分拣口说明" prop="sortingRemark">
        <el-input
          v-model="form.sortingRemark"
          style="width: 100%"
          clearable
          maxlength="100"
          show-word-limit
          placeholder="请输入分拣口说明"
        />
      </el-form-item>
      <el-form-item label="分拣口" prop="sortingArea">
        <el-select
          v-model="form.sortingArea"
          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="sorting-rules">
          <div class="header">
            <span class="mr-10">满足条件</span>
            <el-radio-group v-model="form.matchType">
              <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"
              placeholder="请选择分拣口规则"
              @change="handleConditionTypeChange(item)"
            >
              <el-option
                v-for="rule in getAvailableConditionTypes(index)"
                :key="rule.code"
                :label="rule.desc"
                :value="rule.code"
              />
            </el-select>

            <el-select
              v-model="item.operator"
              style="width: 160px"
              placeholder="请选择关系"
            >
              <el-option
                v-for="operator in operatorList"
                :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"
                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-select
                v-model="item.conditionValue"
                class="platform-select"
                style="width: 160px"
                placeholder="请选择物流公司"
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="1"
                clearable
              >
                <el-option
                  v-for="logistics in logisticsMethodsList"
                  :key="logistics.code"
                  :label="logistics.basicsName"
                  :value="logistics.code"
                />
              </el-select>
            </template>

            <el-button
              v-if="
                (form.conditions?.length ?? 0) <
                (conditionTypeList?.length ?? 0)
              "
              type="primary"
              class="rule-action-btn"
              :icon="Plus"
              size="small"
              circle
              @click="addConditionItem"
            />
            <el-button
              v-if="(form.conditions?.length ?? 0) > 1"
              color="#F56C6C"
              class="rule-action-btn"
              :icon="Minus"
              size="small"
              circle
              plain
              @click="removeConditionItem(index)"
            />
          </div>
        </div>
      </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"
          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, ref } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import platformJson from '@/json/platform.json'
import type {
  Ilogistics,
  IsortingInfo,
  SortingPortAreaItem,
  SortingPortCondition,
  SortingPortOptionItem,
} from '@/types/api/logistics'
import {
  createSortingApi,
  updateSortingApi,
  getSortingConfig,
  getSortingPortAreaListApi,
  getSortPortConditionTypeListApi,
  getSortPortOperatorListApi,
} from '@/api/logistics'

const conditionTypeList = ref<SortingPortOptionItem[]>()
const operatorList = ref<SortingPortOptionItem[]>()

defineProps<{
  logisticsMethodsList: Ilogistics[]
}>()

const emit = defineEmits<{
  success: []
}>()

const visible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const areaList = ref<SortingPortAreaItem[]>([])
const editId = ref<number>()

const createConditionItem = (): SortingPortCondition => ({
  conditionType: '',
  operator: '',
  conditionValue: undefined,
})

const createDefaultForm = (): IsortingInfo => ({
  sortingRemark: '',
  sortingArea: null,
  sortingAreaName: '',
  matchType: 1,
  sortNo: 1,
  conditions: [createConditionItem()],
})

const form = ref<IsortingInfo>(createDefaultForm())

const getAvailableConditionTypes = (currentIndex: number) => {
  const selectedFields = (form.value.conditions ?? [])
    .filter((_, index) => index !== currentIndex)
    .map((item) => item.conditionType)
  return conditionTypeList.value?.filter(
    (rule) => !selectedFields.includes(rule.code),
  )
}

const handleConditionTypeChange = (item: SortingPortCondition) => {
  item.conditionValue = undefined
  item.operator = 'in'
}

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 =
      Array.isArray(item.conditionValue) && item.conditionValue.length > 0
    if (!item.conditionType || !isValueValid || !item.operator) {
      callback(new Error('请完善分拣口规则'))
      return
    }
  }
  callback()
}

const rules = computed(() => ({
  sortingRemark: [
    { required: true, message: '请输入分拣口说明', trigger: 'blur' },
  ],
  sortingArea: [{ required: true, message: '请选择分拣口', trigger: 'change' }],
  conditions: [
    { validator: validateConditions, trigger: 'blur' },
    { required: true, message: '请完善分拣口规则', trigger: 'change' },
  ],
  sortNo: [{ required: true, message: '请输入序号', trigger: 'blur' }],
}))

const platformList = platformJson

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

const addConditionItem = () => {
  form.value.conditions?.push(createConditionItem())
  formRef.value?.validateField('conditions')
}

const removeConditionItem = (index: number) => {
  form.value.conditions?.splice(index, 1)
  formRef.value?.validateField('conditions')
}

const loadAreaList = async () => {
  const res = await getSortingPortAreaListApi()
  if (res.code !== 200) return
  if (!isEdit.value) {
    areaList.value = res.data.filter((item) => item.used === false)
  } else {
    areaList.value = res.data.filter(
      (item) => item.used === false || item.code === form.value.sortingArea,
    )
  }
}

const loadConditionTypeList = async () => {
  const res = await getSortPortConditionTypeListApi()
  if (res.code !== 200) return
  conditionTypeList.value = res.data
}

const loadOperatorList = async () => {
  const res = await getSortPortOperatorListApi()
  if (res.code !== 200) return
  operatorList.value = res.data
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  const submitData: IsortingInfo = {
    ...form.value,
    conditions: (form.value.conditions ?? []).map(
      (item): SortingPortCondition => ({
        ...item,
        conditionValue: Array.isArray(item.conditionValue)
          ? item.conditionValue.join(',')
          : item.conditionValue,
      }),
    ),
  }

  const res = isEdit.value
    ? await updateSortingApi({ ...submitData, id: editId.value })
    : await createSortingApi(submitData)

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

const open = async (item?: IsortingInfo) => {
  isEdit.value = !!item
  editId.value = item?.id
  form.value = createDefaultForm()

  await Promise.all([loadConditionTypeList(), loadOperatorList()])

  if (item?.id) {
    const res = await getSortingConfig({ id: item.id })
    if (res.code !== 200) return
    const conditions = formatConditionsForForm(res.data.conditions ?? [])
    form.value = {
      ...res.data,
      conditions: conditions.length ? conditions : [createConditionItem()],
    }
  }

  await loadAreaList()
  visible.value = true
  formRef.value?.clearValidate()
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.item-info {
  font-size: 12px;
  color: #666;
  line-height: 1;
  margin-top: -15px;
}

.sorting-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>
