<template>
  <div class="tab-content">
    <div class="info-section">
      <div class="section-title-row">
        <div class="section-title-left">
          <span class="section-title-text">ERP供应商信息</span>
        </div>
        <el-button v-if="!isViewMode" type="primary" icon="Document" @click="onSaveClick">保存</el-button>
      </div>

      <el-form ref="erpFormRef" :model="erpForm" :rules="erpFormRules" label-width="120px" class="detail-form">
        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="采购人员：" prop="purchaseId">
              <el-select v-model="erpForm.purchaseId" placeholder="请选择采购人员" class="w-full" filterable :disabled="isViewMode">
                <el-option v-for="item in erpStaffList" :key="item.staffId" :label="`${item.staffCode} , ${item.staffName}`" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购开票类型：" prop="purchaseInvoiceNo">
              <el-select
                v-model="erpForm.purchaseInvoiceNo"
                placeholder="采购开票类型"
                class="w-full"
                filterable
                :disabled="isViewMode"
                @change="handInvoiceChange"
              >
                <el-option v-for="item in purchaseInvoice" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价含税：">
              <el-select v-model="erpForm.unitPrice" placeholder="单价含税" class="w-full" filterable disabled>
                <el-option v-for="item in unitPriceArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="税码：">
              <el-select v-model="erpForm.rateId" placeholder="税码" class="w-full" filterable disabled>
                <el-option v-for="item in taxrateList" :key="item.id" :label="item.taxrateNo" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易币别：">
              <el-select v-model="erpForm.dealCurrencyId" placeholder="请选择交易币别" class="w-full" filterable disabled>
                <el-option v-for="item in currencyList" :key="item.id" :label="item.currencyName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账款归属：">
              <el-input :model-value="supplierNo" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="付款条件：">
              <el-select v-model="erpForm.settlementMethod" placeholder="请选择付款条件" class="w-full" filterable disabled>
                <el-option v-for="dict in payment_clause" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { listErpSupplierInfo, addErpSupplierInfo, updateErpSupplierInfo } from '@/api/supplier/erpSupplierInfo';
import type { ErpSupplierInfoForm } from '@/api/supplier/erpSupplierInfo/types';
import { listErpStaff } from '@/api/erpData/erpStaff';
import type { ErpStaffVO } from '@/api/erpData/erpStaff/types';
import { listComCurrency } from '@/api/company/comCurrency';
import { listTaxrate } from '@/api/company/taxrate';
import type { ComCurrencyVO } from '@/api/company/comCurrency/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { payment_clause } = toRefs<any>(proxy?.useDict('payment_clause'));

const props = defineProps<{
  supplierId?: string | number;
  supplierNo?: string;
  isViewMode: boolean;
}>();

const emit = defineEmits<{
  (e: 'saved'): void;
}>();

const erpFormRef = ref<FormInstance>();
const erpStaffList = ref<ErpStaffVO[]>([]);
const taxrateList = ref<any[]>([]);
const currencyList = ref<ComCurrencyVO[]>([]);

const erpForm = reactive<ErpSupplierInfoForm>({
  id: undefined,
  supplierId: undefined,
  purchaseId: undefined,
  belongingDepartmentId: undefined,
  status: undefined,
  remark: undefined,
  unitPrice: 'True',
  dealCurrencyId: undefined,
  accountBelong: undefined,
  rateId: undefined,
  purchaseInvoiceId: undefined,
  purchaseInvoiceNo: undefined,
  purchaseInvoice: undefined,
  settlementMethod: undefined
});

const erpFormRules: FormRules = {
  purchaseId: [{ required: true, message: '请选择采购人员', trigger: 'change' }],
  purchaseInvoiceNo: [{ required: true, message: '请选择采购开票类型', trigger: 'change' }]
};

const unitPriceArr = ref([
  { label: '含税', value: 'True' },
  { label: '不含税', value: 'False' }
]);

const purchaseInvoice = ref([
  { label: '优易达专票', value: '0001' },
  { label: '江西优易云普票', value: '0016' },
  { label: '江西优易云专票', value: '0006' },
  { label: '无票', value: '0017' },
  { label: '新天利泰专票', value: '0003' },
  { label: '优易达(长沙)-普票', value: '0019' },
  { label: '优易达(长沙)-专票', value: '0018' },
  { label: '优易达普票', value: '0010' },
  { label: '优易智采（江西）-专票', value: '0020' }
]);

const handInvoiceChange = (invoiceNo: any) => {
  const invoice = purchaseInvoice.value.find((item) => item.value === invoiceNo);
  erpForm.purchaseInvoice = invoice?.label;
};

// 加载税码列表并设默认值
const loadTaxrateList = async () => {
  try {
    const res = await listTaxrate({
      isShow: '0',
      pageNum: 1,
      pageSize: 1000
    });
    taxrateList.value = res.rows || [];
    if (!erpForm.rateId && taxrateList.value.length > 0) {
      erpForm.rateId = taxrateList.value[0].id;
    }
  } catch (error) {}
};

// 加载币种列表并设默认值
const loadCurrencyList = async () => {
  try {
    const res = await listComCurrency({
      isShow: '0',
      pageNum: 1,
      pageSize: 1000
    });
    currencyList.value = res.rows || [];
    if (!erpForm.dealCurrencyId && currencyList.value.length > 0) {
      erpForm.dealCurrencyId = currencyList.value[0].id;
    }
  } catch (error) {
    console.error('加载币种列表失败:', error);
    currencyList.value = [];
  }
};

// 加载员工列表
const loadErpStaffList = async () => {
  try {
    const res = await listErpStaff();
    erpStaffList.value = res.rows || [];
  } catch (error) {
    console.error('加载员工列表失败:', error);
  }
};

// 加载已有ERP供应商信息
const loadErpSupplierInfo = async () => {
  if (!props.supplierId) return;

  try {
    const res = await listErpSupplierInfo({ supplierId: props.supplierId, pageNum: 1, pageSize: 1 });
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0];
      Object.assign(erpForm, {
        id: data.id,
        supplierId: data.supplierId,
        purchaseId: data.purchaseId,
        belongingDepartmentId: data.belongingDepartmentId,
        status: data.status,
        remark: data.remark,
        unitPrice: data.unitPrice || 'True',
        dealCurrencyId: data.dealCurrencyId,
        accountBelong: data.accountBelong,
        rateId: data.rateId,
        purchaseInvoiceId: data.purchaseInvoiceId,
        purchaseInvoiceNo: data.purchaseInvoiceNo,
        purchaseInvoice: data.purchaseInvoice,
        settlementMethod: data.settlementMethod
      });
    }
  } catch (error) {
    console.error('加载ERP供应商信息失败:', error);
  }
};

// 监听付款条件字典加载完成后默认选择第一个
watch(
  () => payment_clause.value,
  (val) => {
    if (!erpForm.settlementMethod && val && val.length > 0) {
      erpForm.settlementMethod = val[0].value;
    }
  },
  { immediate: true }
);

// 监听supplierId变化，重新加载ERP数据
watch(
  () => props.supplierId,
  (newId) => {
    if (newId) {
      loadErpSupplierInfo();
    }
  },
  { immediate: true }
);

const onSaveClick = async () => {
  if (!erpFormRef.value) return;

  try {
    await erpFormRef.value.validate();
  } catch {
    return;
  }

  if (!props.supplierId) {
    ElMessage.warning('请先保存基本信息');
    return;
  }

  try {
    const erpData: ErpSupplierInfoForm = {
      ...erpForm,
      supplierId: props.supplierId
    };
    if (erpData.id) {
      await updateErpSupplierInfo(erpData);
    } else {
      await addErpSupplierInfo(erpData);
      // 重新加载以获取新生成的id
      await loadErpSupplierInfo();
    }
    ElMessage.success('ERP供应商信息保存成功');
    emit('saved');
  } catch (error) {
    console.error('保存ERP供应商信息失败:', error);
  }
};

onMounted(() => {
  loadErpStaffList();
  loadTaxrateList();
  loadCurrencyList();
});
</script>

<style scoped>
.tab-content {
  --el-component-size: 24px;
  padding: 16px;
}

.detail-form :deep(.el-form-item__label) {
  white-space: nowrap;
}

.detail-form :deep(.form-row) {
  margin-bottom: 2px;
}

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

.tab-content :deep(.form-row) {
  margin-bottom: 2px;
}

.tab-content :deep(.el-form-item) {
  margin-bottom: 8px;
}

.tab-content :deep(.info-section) {
  margin-bottom: 20px;
}

.tab-content :deep(.section-title-row) {
  margin-bottom: 12px;
  padding-bottom: 8px;
}

.tab-content :deep(.section-title-text) {
  font-size: 14px;
}

.tab-content :deep(.el-form-item__label) {
  font-size: 13px;
  height: var(--el-component-size);
  line-height: var(--el-component-size);
  padding-top: 0;
  padding-bottom: 0;
}

.detail-form :deep(.el-input),
.detail-form :deep(.el-select) {
  width: 100%;
}

.detail-form :deep(.el-input__wrapper),
.detail-form :deep(.el-select__wrapper) {
  min-height: var(--el-component-size);
  height: var(--el-component-size);
  align-items: center;
  padding-top: 0;
  padding-bottom: 0;
}

.detail-form :deep(.el-form-item__content) {
  align-items: center;
  min-height: var(--el-component-size);
}

.detail-form :deep(.el-input__inner) {
  height: var(--el-component-size);
  line-height: var(--el-component-size);
}

.section-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title-left {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.w-full {
  width: 100%;
}
</style>
