<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="22">
            <span>企业采购习惯</span>
          </el-col>
        </el-row>
      </template>

      <el-form ref="purchaseHabitFormRef" :model="form" :rules="rules" label-width="140px">
        <!-- 基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月度采购金额预估" prop="monthPurchase">
              <el-input v-model="form.monthPurchase" placeholder="请输入月度采购金额预估" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年度采购金额" prop="yearPurchase">
              <el-input v-model="form.yearPurchase" placeholder="请输入年度采购金额" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产品选择 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品选型" prop="choiceModel">
              <el-radio-group v-model="form.choiceModel">
                <el-radio v-for="dict in product_types_choosing" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 日常打印量 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="日常打印量" prop="printAmount">
              <el-radio-group v-model="form.printAmount">
                <el-radio v-for="dict in daily_print_volume" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 购买选项 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买原装耗材" prop="buyOriginal">
              <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-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="专人进行技术服务" prop="technologyService">
              <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-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="主要办公采购类目" prop="purchaseCategory">
              <el-checkbox-group v-model="purchaseCategoryArr">
                <el-checkbox v-for="dict in purchase_item" :key="dict.value" :value="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="otherCategory">
              <el-input v-model="form.otherCategory" type="textarea" :rows="2" placeholder="其他采购品类" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 企业福利 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="企业福利" prop="adaptScene">
              <el-checkbox-group v-model="adaptSceneArr">
                <el-checkbox v-for="dict in welfare_item" :key="dict.value" :value="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="otherScene">
              <el-input v-model="form.otherScene" type="textarea" :rows="2" placeholder="其他企业福利" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产品定制需求 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品定制需求" prop="customizeDemand">
              <el-checkbox-group v-model="customizeDemandArr">
                <el-checkbox v-for="dict in product_customization" :key="dict.value" :value="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="otherCustomize">
              <el-input v-model="form.otherCustomize" type="textarea" :rows="2" placeholder="其他定制化需求" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交按钮 -->
        <el-row :gutter="20">
          <el-col :span="24" class="text-center">
            <el-button @click="goBack">取消</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="PurchaseHabit" lang="ts">
import {
  listPurchaseHabit,
  getPurchaseHabit,
  delPurchaseHabit,
  addPurchaseHabit,
  updatePurchaseHabit,
  getCustomerPurchaseHabitData
} from '@/api/customer/customerFile/purchaseHabit';
import { PurchaseHabitVO, PurchaseHabitQuery, PurchaseHabitForm } from '@/api/customer/customerFile/purchaseHabit/types';

// 接收父组件传递的props
const props = defineProps<{
  customerId?: string;
  customerNo?: string;
  customerName?: string;
}>();

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 purchaseHabitList = ref<PurchaseHabitVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const router = useRouter();
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const adaptSceneArr = ref<Array<string | number>>([]);
const purchaseCategoryArr = ref<Array<string | number>>([]);
const customizeDemandArr = ref<Array<string | number>>([]);

const queryFormRef = ref<ElFormInstance>();
const purchaseHabitFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PurchaseHabitForm = {
  id: undefined,
  customerId: undefined,
  customerNo: undefined,
  monthPurchase: undefined,
  yearPurchase: undefined,
  permanentOfficer: undefined,
  choiceModel: undefined,
  printAmount: undefined,
  buyOriginal: '1',
  technologyService: '1',
  purchaseCategory: undefined,
  otherCategory: undefined,
  adaptScene: undefined,
  otherScene: undefined,
  customizeDemand: undefined,
  otherCustomize: undefined,
  remark: undefined
};
const data = reactive<PageData<PurchaseHabitForm, PurchaseHabitQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    customerNo: undefined,
    monthPurchase: undefined,
    yearPurchase: undefined,
    permanentOfficer: undefined,
    choiceModel: undefined,
    printAmount: undefined,
    buyOriginal: undefined,
    technologyService: undefined,
    purchaseCategory: undefined,
    otherCategory: undefined,
    adaptScene: undefined,
    otherScene: undefined,
    customizeDemand: undefined,
    otherCustomize: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    buyOriginal: [{ required: true, message: '是否购买原装耗材不能为空', trigger: 'change' }],
    technologyService: [{ required: true, message: '是否购买技术服务不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询客户采购习惯列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPurchaseHabit(queryParams.value);
  purchaseHabitList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 加载客户采购画像数据 */
const loadCustomerPurchaseData = async () => {
  if (!props.customerId) return;

  try {
    loading.value = true;
    const res = await getCustomerPurchaseHabitData(props.customerId);
    if (res.data) {
      Object.assign(form.value, res.data);

      // 将字符串转换为数组并赋值给对应的数组变量
      if (form.value.purchaseCategory && typeof form.value.purchaseCategory === 'string') {
        purchaseCategoryArr.value = form.value.purchaseCategory.split(',').filter((item: string) => item.trim());
      } else {
        purchaseCategoryArr.value = [];
      }

      if (form.value.adaptScene && typeof form.value.adaptScene === 'string') {
        adaptSceneArr.value = form.value.adaptScene.split(',').filter((item: string) => item.trim());
      } else {
        adaptSceneArr.value = [];
      }

      if (form.value.customizeDemand && typeof form.value.customizeDemand === 'string') {
        customizeDemandArr.value = form.value.customizeDemand.split(',').filter((item: string) => item.trim());
      } else {
        customizeDemandArr.value = [];
      }
    } else {
      // 如果没有数据，设置客户编号并初始化数组
      form.value.customerId = props.customerId;
      form.value.customerNo = props.customerNo;
      purchaseCategoryArr.value = [];
      adaptSceneArr.value = [];
      customizeDemandArr.value = [];
    }
  } catch (error) {
    console.error('加载采购画像数据失败:', error);
    // 如果加载失败，设置客户编号并初始化数组
    form.value.customerId = props.customerId;
    form.value.customerNo = props.customerNo;
    purchaseCategoryArr.value = [];
    adaptSceneArr.value = [];
    customizeDemandArr.value = [];
  } finally {
    loading.value = false;
  }
};
const goBack = () => {
  router.push('/customer/customer-file/customer-list');
};

/** 提交按钮 */
const submitForm = () => {
  purchaseHabitFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      // 将数组变量转换为逗号分隔的字符串并赋值给form字段
      form.value.purchaseCategory = purchaseCategoryArr.value.join(',');
      form.value.adaptScene = adaptSceneArr.value.join(',');
      form.value.customizeDemand = customizeDemandArr.value.join(',');

      try {
        if (form.value.id) {
          await updatePurchaseHabit(form.value);
        } else {
          await addPurchaseHabit(form.value);
        }
        proxy?.$modal.msgSuccess('保存成功');
        // 重新加载数据
        await loadCustomerPurchaseData();
      } catch (error) {
        console.error('保存失败:', error);
        proxy?.$modal.msgError('保存失败，请重试');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PurchaseHabitVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户采购习惯编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delPurchaseHabit(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/purchaseHabit/export',
    {
      ...queryParams.value
    },
    `purchaseHabit_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  // 页面加载时根据客户编号查询采购画像数据
  loadCustomerPurchaseData();
});

// 监听props变化
watch(
  () => props.customerId,
  (newCustomerId) => {
    if (newCustomerId) {
      loadCustomerPurchaseData();
    }
  }
);
</script>
