<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :rules="rules" :inline="true" label-width="80px">
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="queryParams.manageCom" clearable placeholder="请输入管理机构">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredManagecom"
                  :key="dict.dictValue"
                  :label="dict.dictValue + '-' + dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="科目代码" prop="finItemCode">
              <el-select v-model="queryParams.finItemCode" placeholder="请选择科目编号" clearable @change="finItemChangeQury">
                <template #header>
                  <el-input v-model="likeFinItemName" placeholder="可根据科目代码或名称模糊查询" @input="filterByFinItemName"></el-input>
                </template>
                <el-option
                  v-for="option in filteredFinItem"
                  :key="option.finItemCode"
                  :label="option.finItemCode + '-' + option.finItemName"
                  :value="option.finItemCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="明细科目" prop="subItemCode">
              <el-select v-model="queryParams.subItemCode" clearable placeholder="请选择明细科目" >
                <template #header>
                  <el-input v-model="likeSubItemName" placeholder="可根据明细科目代码或名称模糊查询" @input="filterBySubItemName"></el-input>
                </template>
                <el-option
                  v-for="option in filteredSubItem"
                  :key="option.subItemCode"
                  :label="option.subItemCode + '-' + option.subItemName"
                  :value="option.subItemCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="记账日期" prop="dateRange">
              <el-date-picker
                v-model="queryParams.dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDateRangeChange"
                clearable
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button v-hasPermi="['bfs:subjecttrans:export']" icon="Download" type="success" @click="handleExport">导出</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="subjectTransList">
        <el-table-column label="管理机构" align="center" prop="manageCom" width="100px" />
        <el-table-column label="场景编码" align="center" prop="costId" width="100px" />
        <el-table-column label="业务号" align="center" prop="businessNo" width="200px" />
        <el-table-column label="保单号" align="center" prop="policyNo" width="200px" />
        <el-table-column label="记账日期" align="center" prop="arrivalDate" width="150px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="科目代码" align="center" prop="finItemCode" width="150px" />
        <el-table-column label="科目描述" align="center" prop="finItemName" width="200px" />
        <el-table-column label="明细科目" align="center" prop="subItemCode" width="150px" />
        <el-table-column label="明细描述" align="center" prop="subItemName" width="200px" />
        <el-table-column label="凭证号" align="center" prop="belnrSap" width="200px" />
        <el-table-column label="借方金额" align="center" prop="debitBalance" width="150px" />
        <el-table-column label="贷方金额" align="center" prop="creditBalance" width="150px" />
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="SubjectTrans" lang="ts">
import {getCacheInterList, getCacheList, getSubjectTransList} from '@/api/bfs/busnessQury/costBalance';
import {queryManageCom} from "@/api/bfs/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const total = ref(0);
const showSearch = ref(true);
const loading = ref(false);
const subjectTransList = ref([]);
const queryFormRef = ref<ElFormInstance>();
const certificateList = ref([]);
const costList = ref([]);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageCom: undefined,
    finItemCode: undefined,
    subItemCode: undefined,
    dateRange: undefined
  },
  rules: {
    manageCom: [{ required: true, message: '管理机构不能为空', trigger: 'blur' }],
    dateRange: [{ required: true, message: '记账日期不能为空', trigger: 'blur' }]
  }
});
const { queryParams, rules } = toRefs(data);
const likeName = ref('');
const filteredManagecom = ref([]);
const likeFinItemName = ref('');
const filteredFinItem = ref([]);
const likeSubItemName = ref('');
const filteredSubItem = ref([]);
const selectSubItemList = ref([]);
const sys_managecomCache = ref([]);

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 查询科目余额 */
const getList = async () => {
  queryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const res = await getSubjectTransList(proxy?.addDateRange(queryParams.value, queryParams.value.dateRange));
      subjectTransList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    }
  });
};

/** 查询字典下拉信息 */
const getCache = async () => {
  const res = await getCacheInterList();
  certificateList.value = res.data.certificateList;
  costList.value = res.data.costList;
  filteredFinItem.value = certificateList.value;
  filteredSubItem.value = costList.value;
};
/** 导出按钮操作 */
const handleExport = () => {
  queryParams.value = proxy?.addDateRange(queryParams.value, queryParams.value.dateRange);
  proxy?.download(
    'bfs/bussnessQury/exportSubjectTransList',
    {
      ...queryParams.value
    },
    `往来业务_${new Date().getTime()}.xlsx`
  );
};

/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecomCache.value.filter((item) => {
      return item.dictLabel.includes(likeName.value) || item.dictValue.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecomCache.value;
  }
};

const filterByFinItemName = () => {
  if (likeFinItemName.value) {
    filteredFinItem.value = certificateList.value.filter((item) => {
      return item.finItemCode.includes(likeFinItemName.value) || item.finItemName.includes(likeFinItemName.value);
    });
  } else {
    filteredFinItem.value = certificateList.value;
  }
};

const filterBySubItemName = () => {
  if (selectSubItemList.value.length > 0) {
    if (likeSubItemName.value) {
      filteredSubItem.value = selectSubItemList.value.filter((item) => {
        return item.subItemCode.includes(likeSubItemName.value) || item.subItemName.includes(likeSubItemName.value);
      });
    } else {
      filteredSubItem.value = selectSubItemList.value;
    }
  } else {
    if (likeSubItemName.value) {
      filteredSubItem.value = costList.value.filter((item) => {
        return item.subItemCode.includes(likeSubItemName.value) || item.subItemName.includes(likeSubItemName.value);
      });
    } else {
      filteredSubItem.value = costList.value;
    }
  }
};

const finItemChangeQury = () => {
  if (queryParams.value.finItemCode) {
    selectSubItemList.value = costList.value.filter((item) => {
      return item.finItemCode === queryParams.value.finItemCode;
    });
    filteredSubItem.value = selectSubItemList.value;
  } else {
    selectSubItemList.value = [];
  }
  likeSubItemName.value = undefined;
};

// 计算属性用于动态设置 picker options
const handleDateRangeChange = (value: [string, string] | null) => {
  if (!value || !value[0] || !value[1]) return;

  const startDate = new Date(value[0]);
  const endDate = new Date(value[1]);

  const maxEndDate = new Date(startDate);
  maxEndDate.setDate(maxEndDate.getDate() + 365);

  if (endDate > maxEndDate) {
    proxy.$modal.msgError('结束日期不能超过开始日期一年以上');
    queryParams.value.dateRange = ['', ''];
  }
};

const getCacheManageCom = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};

onMounted(() => {
  getCache();
  getCacheManageCom();
});
</script>

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