<template>
  <el-drawer v-model="drawerVisible" title="凭证提取定义" :close-on-click-modal="true" :destroy-on-close="true" size="70%">
    <el-card shadow="hover">
      <template #header>
        <el-text size="small">过滤条件</el-text>
        <el-button type="primary" v-hasPermi="['bfs:elementsMapping:save']" size="small" @click="addFilterFormItem">添加</el-button>
      </template>
      <div v-for="(filterItem, index) in filterFormRef" :key="index">
        <el-form :ref="`filterForm${index}`" :inline="true" label-width="60px">
          <el-row>
            <el-form-item label="数据要素" :prop="`filterFormRef[${index}].accounting`">
              <el-select v-model="filterItem.accounting" size="small" placeholder="请选数据要素" style="width: 140px">
                <el-option v-for="option in dataElements" :key="option.elementCode" :label="option.elementName" :value="option.elementCode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="获取方式" :prop="`filterFormRef[${index}].method`">
              <el-select v-model="filterItem.method" size="small" @change="filterMethodSelect(index)" placeholder="请选择获取方式" style="width: 140px">
                <el-option
                  v-for="option in DataTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  :disabled="option.value === 'variable'"
                  style="width: 230px"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="filterItem.method === 'fixed'" label="要素值" :prop="`basicFormRef[${index}].valueFixed`">
              <el-input v-model="filterItem.valueFixed" size="small" style="width: 140px"></el-input>
            </el-form-item>
            <el-form-item v-if="filterItem.method === 'formula'" label="要素公式" :prop="`basicFormRef[${index}].valueFormula`">
              <el-input v-model="filterItem.valueFormula" size="small" style="width: 240px"></el-input>
            </el-form-item>
            <el-button type="danger" v-hasPermi="['bfs:elementsMapping:save']" size="small" @click="removeFilterFormItem(index)">删除</el-button>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <!-- 基础信息表单 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <template #header>
        <el-text size="small">凭证基础信息提取</el-text>
      </template>
      <div v-for="(basicItem, index) in basicFormRef" :key="index">
        <el-form :ref="`basicForm${index}`" :inline="true" label-width="60px">
          <el-row>
            <el-form-item label="科目要素" :prop="`basicFormRef[${index}].accounting`">
              <el-select v-model="basicItem.accounting" size="small" placeholder="请选择科目要素" style="width: 140px">
                <el-option v-for="option in basicElements" :key="option.elementCode" :label="option.elementName" :value="option.elementCode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="获取方式" :prop="`basicFormRef[${index}].method`">
              <el-select v-model="basicItem.method" size="small" @change="basicMethodSelect(index)" placeholder="请选择获取方式" style="width: 140px">
                <el-option v-for="option in DataTypeOptions" :key="option.value" :label="option.label" :value="option.value" style="width: 230px">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicItem.method === 'fixed'" label="要素值" :prop="`basicFormRef[${index}].valueFixed`">
              <el-input v-model="basicItem.valueFixed" size="small" style="width: 140px"></el-input>
            </el-form-item>
            <el-form-item v-if="basicItem.method === 'variable'" label="要素值" :prop="`basicFormRef[${index}].valueVariable`">
              <el-select v-model="basicItem.valueVariable" size="small" placeholder="类型" style="width: 140px">
                <el-option v-for="option in dataElements" :key="option.elementCode" :label="option.elementName" :value="option.elementCode" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicItem.method === 'formula'" label="要素公式" :prop="`basicFormRef[${index}].valueFormula`">
              <el-input v-model="basicItem.valueFormula" size="small" style="width: 240px"></el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <!-- 辅助核算表单 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <template #header>
        <el-text size="small">辅助核算项提取</el-text>
        <el-button type="primary" size="small" v-hasPermi="['bfs:elementsMapping:save']" @click="addAuxiFormItem">添加</el-button>
      </template>
      <div v-for="(auxiItem, index) in auxiFormRef" :key="index">
        <el-form :ref="`auxiForm${index}`" :inline="true" label-width="60px">
          <el-row>
            <el-form-item label="科目要素" :prop="`auxiFormRef[${index}].accounting`">
              <el-select v-model="auxiItem.accounting" size="small" placeholder="请选择科目要素" style="width: 140px">
                <el-option v-for="option in auxiElements" :key="option.elementCode" :label="option.elementName" :value="option.elementCode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="获取方式" :prop="`auxiFormRef[${index}].method`">
              <el-select v-model="auxiItem.method" size="small" @change="auxiMethodSelect(index)" placeholder="请选择获取方式" style="width: 140px">
                <el-option v-for="option in DataTypeOptions" :key="option.value" :label="option.label" :value="option.value" style="width: 230px">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="auxiItem.method === 'fixed'" label="要素值" :prop="`auxiFormRef[${index}].valueFixed`">
              <el-input v-model="auxiItem.valueFixed" size="small" style="width: 140px"></el-input>
            </el-form-item>
            <el-form-item v-if="auxiItem.method === 'variable'" label="要素值" :prop="`auxiFormRef[${index}].valueVariable`">
              <el-select v-model="auxiItem.valueVariable" size="small" placeholder="类型" style="width: 140px">
                <el-option v-for="option in dataElements" :key="option.elementCode" :label="option.elementName" :value="option.elementCode" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="auxiItem.method === 'formula'" label="要素公式" :prop="`auxiFormRef[${index}].valueFormula`">
              <el-input v-model="auxiItem.valueFormula" size="small" style="width: 240px"></el-input>
            </el-form-item>
            <el-button type="danger" v-hasPermi="['bfs:elementsMapping:save']" size="small" @click="removeAuxiFormItem(index)">删除</el-button>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card shadow="hover" style="margin-top: 20px">
      <el-button v-hasPermi="['bfs:elementsMapping:save']" type="primary" size="small" style="margin-left: 20px" @click="saveCostType">保存</el-button>
    </el-card>
  </el-drawer>
</template>

<script setup lang="ts">
import { getFinElements, getFinElementsMapping, saveFinElementsMapping } from '@/api/bfs/fiCertificateType/CostDrawer';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  visible: Boolean,
  costId: Object,
  finItemCode: Object,
  finItemType: Object,
  certificateId: Object,
  finData: Object
});
const drawerVisible = ref(props.visible);
const CostId = ref('');
const FinItemType = ref('');
const FinItemCode = ref('');
const FinData = ref({});
const CertificateId = ref('');
const loading = ref(false);

const emit = defineEmits(['update:visible']);
//基础要素
const basicElements = ref([]);
//辅助核算项要素
const auxiElements = ref([]);
//数据要素
const dataElements = ref([]);

const DataTypeOptions = ref([
  { value: 'fixed', label: '固定值' },
  { value: 'variable', label: '变量' },
  { value: 'formula', label: '公式' }
]);

//过滤条件表单数据
const filterFormRef = ref([
  {
    accounting: '',
    method: '',
    valueFixed: '',
    valueFormula: ''
  }
]);
// 基础信息表单数据
const basicFormRef = ref([
  {
    accounting: '',
    method: '',
    valueFixed: '',
    valueVariable: '',
    valueFormula: ''
  }
]);

// 辅助核算表单数据
const auxiFormRef = ref([
  {
    accounting: '',
    method: '',
    valueFixed: '',
    valueVariable: '',
    valueFormula: ''
  }
]);

const updateFromProps = async () => {
  loading.value = true;
  const { costId, finItemType, finItemCode, certificateId, finData } = props;
  CostId.value = costId;
  FinItemType.value = finItemType;
  FinItemCode.value = finItemCode;
  CertificateId.value = certificateId;
  FinData.value = finData;
  if (CostId.value) {
    const res = await getFinElementsMapping(CostId.value, FinItemCode.value, FinItemType.value);
    if (res.data.basicForm.length > 0) {
      basicFormRef.value = [];
      basicFormRef.value = res.data.basicForm;
    } else {
      initBasicForm();
    }

    if (res.data.filterForm.length > 0) {
      filterFormRef.value = res.data.filterForm;
    } else {
      initFilterForm();
    }

    auxiFormRef.value = res.data.auxiForm;
  }
  loading.value = false;
};

const getElements = async () => {
  const res = await getFinElements();
  basicElements.value = res.data.basicElements;
  auxiElements.value = res.data.auxiElements;
  dataElements.value = res.data.dataElements;
  // initBasicForm();
};

// 添加过滤表单项
const addFilterFormItem = () => {
  filterFormRef.value.push({
    accounting: '',
    method: '',
    valueFixed: '',
    valueFormula: ''
  });
};

// 添加辅助核算表单项
const addAuxiFormItem = () => {
  auxiFormRef.value.push({
    accounting: '',
    method: '',
    valueFixed: '',
    valueVariable: '',
    valueFormula: ''
  });
};

const initBasicForm = () => {
  basicFormRef.value = [];
  for (const element of basicElements.value) {
    let Method = '';
    let ValueFixed = '';
    let ValueVariable = '';
    let ValueFormula = '';
    if (element.elementCode === 'certificate_id') {
      Method = 'fixed';
      ValueFixed = FinData.value.certificateId;
    } else if (element.elementCode === 'cost_id') {
      Method = 'fixed';
      ValueFixed = FinData.value.costId;
    } else if (element.elementCode === 'fin_item_type') {
      Method = 'fixed';
      ValueFixed = FinData.value.finItemType;
    } else if (element.elementCode === 'fin_item_code') {
      Method = 'fixed';
      ValueFixed = FinData.value.finItemCode;
    } else if (element.elementCode === 'sub_item_code') {
      Method = 'fixed';
      ValueFixed = FinData.value.subItemCode;
    }

    basicFormRef.value.push({
      accounting: element.elementCode,
      method: Method,
      valueFixed: ValueFixed,
      valueVariable: ValueVariable,
      valueFormula: ValueFormula
    });
  }
};

const initFilterForm = () => {
  filterFormRef.value = [];
  filterFormRef.value.push({
    accounting: 'buss_type',
    method: 'fixed',
    valueFixed: FinData.value.costId
  });
};

const saveCostType = () => {
  const basicForm = basicFormRef.value;
  const filterForm = filterFormRef.value;
  const auxiForm = auxiFormRef.value;
  const data = {
    costId: CostId.value,
    finItemType: FinItemType.value,
    certificateId: CertificateId.value,
    finItemCode: FinItemCode.value,
    basicForm,
    filterForm,
    auxiForm
  };
  saveFinElementsMapping(data).then((res) => {
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('保存成功！');
    }
  });
};

// 删除过滤表单项
const removeFilterFormItem = (index: number) => {
  filterFormRef.value.splice(index, 1);
};

// 删除辅助核算表单项
const removeAuxiFormItem = (index: number) => {
  auxiFormRef.value.splice(index, 1);
};

// 选择过滤表单项的获取方法后清空已填写信息
const filterMethodSelect = (index: number) => {
  filterFormRef.value[index].valueFixed = '';
  filterFormRef.value[index].valueFormula = '';
};

// 选择过滤表单项的获取方法后清空已填写信息
const basicMethodSelect = (index: number) => {
  basicFormRef.value[index].valueFixed = '';
  basicFormRef.value[index].valueVariable = '';
  basicFormRef.value[index].valueFormula = '';
};

// 选择过滤表单项的获取方法后清空已填写信息
const auxiMethodSelect = (index: number) => {
  auxiFormRef.value[index].valueFixed = '';
  auxiFormRef.value[index].valueVariable = '';
  auxiFormRef.value[index].valueFormula = '';
};

// 确保 drawerVisible 和父组件的 visible 属性同步
watch(
  () => props.visible,
  (newVal) => {
    drawerVisible.value = newVal;
  }
);
watch(drawerVisible, (newVal) => {
  emit('update:visible', newVal);
});
// 监听 props 的变化以更新内部状态
watch(
  () => ({
    costId: props.costId,
    finItemType: props.finItemType,
    finItemCode: props.finItemCode,
    certificateId: props.certificateId,
    finData: props.finData
  }),
  ({ costId, finItemType, finItemCode, certificateId, finData }) => {
    updateFromProps();
  },
  { immediate: true, deep: true } // 使用 immediate 和 deep 来立即运行并深度监听
);

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

<style scoped lang="scss"></style>
