<template>
  <div class="purchase-habit-container">
    <!-- 顶部返回 -->
    <div class="page-header">
      <el-button link @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回</span>
      </el-button>
      <span class="page-title">企业采购习惯</span>
    </div>

    <div class="page-content">
      <el-form ref="formRef" :model="form" label-position="top">
        <!-- 采购金额 -->
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="月度采购金额">
              <el-input v-model="form.monthlyAmount" placeholder="请输入">
                <template #suffix>万</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年度采购金额">
              <el-input v-model="form.yearlyAmount" placeholder="请输入">
                <template #suffix>万</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产品选型 -->
        <el-form-item label="产品选型">
          <div class="tag-group">
            <div
              v-for="item in productTypeOptions"
              :key="item"
              :class="['tag-item', { active: form.productTypes.includes(item) }]"
              @click="toggleTag(form.productTypes, item)"
            >
              {{ item }}
            </div>
          </div>
        </el-form-item>

        <!-- 日常打印量 -->
        <el-form-item label="日常打印量">
          <div class="tag-group">
            <div
              v-for="item in printVolumeOptions"
              :key="item"
              :class="['tag-item', { active: form.printVolume === item }]"
              @click="form.printVolume = item"
            >
              {{ item }}
            </div>
          </div>
        </el-form-item>

        <!-- 购买原装耗材 & 专人进行技术服务 -->
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="购买原装耗材">
              <el-radio-group v-model="form.buyOriginal">
                <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专人进行技术服务">
              <el-radio-group v-model="form.technologyService">
                <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 主要办公采购类目 -->
        <el-form-item label="主要办公采购类目">
          <div class="tag-group">
            <div
              v-for="item in categoryOptions"
              :key="item"
              :class="['tag-item', { active: form.categories.includes(item) }]"
              @click="toggleTag(form.categories, item)"
            >
              {{ item }}
            </div>
          </div>
          <el-input v-model="form.otherCategory" placeholder="其他采购类目" maxlength="50" show-word-limit class="other-input" />
        </el-form-item>

        <!-- 企业福利 -->
        <el-form-item label="企业福利">
          <div class="tag-group">
            <div
              v-for="item in welfareOptions"
              :key="item"
              :class="['tag-item', { active: form.welfares.includes(item) }]"
              @click="toggleTag(form.welfares, item)"
            >
              {{ item }}
            </div>
          </div>
          <el-input v-model="form.otherScene" placeholder="其他福利" maxlength="50" show-word-limit class="other-input" />
        </el-form-item>

        <!-- 产品定制需求 -->
        <el-form-item label="产品定制需求">
          <div class="tag-group">
            <div
              v-for="item in customOptions"
              :key="item"
              :class="['tag-item', { active: form.customs.includes(item) }]"
              @click="toggleTag(form.customs, item)"
            >
              {{ item }}
            </div>
          </div>
          <el-input v-model="form.otherCustomize" placeholder="其他需求" maxlength="50" show-word-limit class="other-input" />
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button type="danger" @click="handleSave">保存</el-button>
        <el-button @click="handleBack">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, getCurrentInstance, toRefs, onMounted, ComponentInternalInstance, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { updatePurchaseHabit, getCustomerPurchaseHabitData } from '@/api/pc/enterprise/purchaseHabit';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { welfare_item, sys_platform_yes_no, product_types_choosing, purchase_item, product_customization, daily_print_volume } = toRefs<any>(
  proxy?.useDict('welfare_item', 'sys_platform_yes_no', 'product_types_choosing', 'purchase_item', 'product_customization', 'daily_print_volume')
);

const router = useRouter();

// 根据字典数据生成选项
const productTypeOptions = computed(() => product_types_choosing.value?.map((item: any) => item.label) || []);
const printVolumeOptions = computed(() => daily_print_volume.value?.map((item: any) => item.label) || []);
const categoryOptions = computed(() => purchase_item.value?.map((item: any) => item.label) || []);
const welfareOptions = computed(() => welfare_item.value?.map((item: any) => item.label) || []);
const customOptions = computed(() => product_customization.value?.map((item: any) => item.label) || []);

const form = reactive({
  id: undefined,
  customerId: undefined,
  customerNo: '',
  permanentOfficer: '',
  monthlyAmount: '',
  yearlyAmount: '',
  productTypes: [] as string[],
  printVolume: '',
  printAmount: '',
  buyOriginal: '',
  technologyService: '',
  categories: [] as string[],
  otherCategory: '',
  welfares: [] as string[],
  customs: [] as string[],
  adaptScenes: [] as string[],
  otherScene: '',
  otherCustomize: '',
  choiceModel: '',
  remark: ''
});

const toggleTag = (arr: string[], item: string) => {
  const index = arr.indexOf(item);
  if (index > -1) arr.splice(index, 1);
  else arr.push(item);
};
const handleBack = () => {
  router.push('/enterprise/companyInfo');
};
const handleSave = async () => {
  try {
    // 将表单数据映射为接口所需格式
    const submitData = {
      id: form.id,
      customerId: form.customerId,
      customerNo: form.customerNo,
      monthPurchase: form.monthlyAmount ? parseFloat(form.monthlyAmount) : undefined,
      yearPurchase: form.yearlyAmount ? parseFloat(form.yearlyAmount) : undefined,
      permanentOfficer: form.permanentOfficer,
      choiceModel: form.productTypes.length > 0 ? product_types_choosing.value?.find((i: any) => i.label === form.productTypes[0])?.value || '' : '',
      printAmount: form.printVolume ? daily_print_volume.value?.find((i: any) => i.label === form.printVolume)?.value || '' : '',
      buyOriginal: form.buyOriginal,
      technologyService: form.technologyService,
      purchaseCategory:
        form.categories.length > 0
          ? form.categories
              .map((label) => {
                const item = purchase_item.value?.find((i: any) => i.label === label);
                return item ? item.value : '';
              })
              .filter(Boolean)
              .join(',')
          : undefined,
      otherCategory: form.otherCategory || undefined,
      adaptScene:
        form.welfares.length > 0
          ? form.welfares
              .map((label) => {
                const item = welfare_item.value?.find((i: any) => i.label === label);
                return item ? item.value : '';
              })
              .filter(Boolean)
              .join(',')
          : undefined,
      otherScene: form.otherScene || undefined,
      customizeDemand:
        form.customs.length > 0
          ? form.customs
              .map((label) => {
                const item = product_customization.value?.find((i: any) => i.label === label);
                return item ? item.value : '';
              })
              .filter(Boolean)
              .join(',')
          : undefined,
      otherCustomize: form.otherCustomize || undefined,
      remark: form.remark || undefined
    };

    await updatePurchaseHabit(submitData);
    ElMessage.success('保存成功');
    handleBack();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const getPurchaseHabitData = async () => {
  try {
    const res = await getCustomerPurchaseHabitData();
    if (res.code === 200 && res.data) {
      const data = res.data;

      // 映射数据到表单
      form.id = data.id;
      form.customerId = data.customerId;
      form.customerNo = data.customerNo || '';
      form.permanentOfficer = data.permanentOfficer || '';
      form.monthlyAmount = data.monthPurchase || '';
      form.yearlyAmount = data.yearPurchase || '';

      // 处理产品选型（单选）
      form.productTypes = data.choiceModel ? [product_types_choosing.value?.find((i: any) => i.value === data.choiceModel)?.label || ''] : [];

      // 处理日常打印量（单选）
      form.printVolume = data.printAmount ? daily_print_volume.value?.find((i: any) => i.value === data.printAmount)?.label || '' : '';

      form.categories = data.purchaseCategory
        ? data.purchaseCategory
            .split(',')
            .map((id: string) => {
              const item = purchase_item.value?.find((i: any) => i.value === id);
              return item ? item.label : '';
            })
            .filter(Boolean)
        : [];

      form.welfares = data.adaptScene
        ? data.adaptScene
            .split(',')
            .map((id: string) => {
              const item = welfare_item.value?.find((i: any) => i.value === id);
              return item ? item.label : '';
            })
            .filter(Boolean)
        : [];

      form.customs = data.customizeDemand
        ? data.customizeDemand
            .split(',')
            .map((id: string) => {
              const item = product_customization.value?.find((i: any) => i.value === id);
              return item ? item.label : '';
            })
            .filter(Boolean)
        : [];

      // 处理单选字段
      form.printAmount = data.printAmount || '';

      form.buyOriginal = data.buyOriginal || '';

      form.technologyService = data.technologyService;

      form.choiceModel = data.choiceModel || '';

      // 其他字段
      form.otherCategory = data.otherCategory || '';
      form.otherCustomize = data.otherCustomize || '';
      form.otherScene = data.otherScene || '';
      form.otherCustomize = data.otherCustomize || '';
      form.remark = data.remark || '';
    }
  } catch (error) {
    console.error('获取采购习惯数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

onMounted(() => {
  getPurchaseHabitData();
});
</script>

<style scoped lang="scss">
.purchase-habit-container {
  background: #f5f5f5;
  min-height: 100%;
}
.page-header {
  background: #fff;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #eee;
  .page-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}
.page-content {
  padding: 20px;
  background: #fff;
  margin: 20px;
  border-radius: 8px;
}
.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  .tag-item {
    padding: 8px 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    color: #666;
    transition: all 0.2s;
    &:hover {
      border-color: #e60012;
      color: #e60012;
    }
    &.active {
      border-color: #e60012;
      color: #e60012;
      background: #fff5f5;
    }
  }
}
.other-input {
  margin-top: 10px;
}
.form-footer {
  text-align: center;
  padding-top: 30px;
  border-top: 1px solid #eee;
  margin-top: 20px;
}
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}
:deep(.el-radio) {
  margin-right: 30px;
}
</style>
