<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="costId">
              <el-select v-model="queryParams.costId" clearable placeholder="请选择场景编码" >
                <template #header>
                  <el-input v-model="likeCostName" placeholder="可根据明细科目代码或名称模糊查询" @input="filterByCostIdName"></el-input>
                </template>
                <el-option
                  v-for="option in filteredCostList"
                  :key="option.costId"
                  :label="option.costId + '-' + option.costName"
                  :value="option.costId"
                >
                </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="结束日期"
                clearable
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="渠道" prop="saleChnl">
              <el-select v-model="queryParams.saleChnl" placeholder="请选择渠道" clearable>
                <el-option
                  v-for="dict in bfs_sale_chnl"
                  :key="dict.value"
                  :label="dict.value + '-' + dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="险种" prop="riskCode">
              <el-select v-model="queryParams.riskCode" clearable placeholder="请输入险种">
                <template #header>
                  <el-input v-model="likeProductName" placeholder="可根据险种编码或名称模糊查询" @input="filterByPorduct"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredProductList"
                  :key="dict.productCode"
                  :label="dict.productCode + '-' + dict.productName"
                  :value="dict.productCode"
                ></el-option>
              </el-select>
            </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 icon="Download" v-hasPermi="['bfs:costbalance:export']" 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="costBalanceList">
        <el-table-column label="机构" align="center" prop="manageCom" />
        <el-table-column label="场景编码" align="center" prop="costId" />
        <el-table-column label="场景名称" align="center" prop="costName" />
        <el-table-column label="科目代码" align="center" prop="finItemCode" />
        <el-table-column label="科目描述" align="center" prop="finItemName" />
        <el-table-column label="明细科目" align="center" prop="subItemCode" />
        <el-table-column label="明细科目描述" align="center" prop="subItemName" />
        <el-table-column label="渠道" align="center" prop="saleChnl" />
        <el-table-column label="险种" align="center" prop="riskCode" />
        <el-table-column label="累计借方金额" align="center" prop="debitBalance" />
        <el-table-column label="累计贷方金额" align="center" prop="creditBalance" />
      </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="CostBalanceQury" lang="ts">
import { CostBalanceList, getCacheList } from '@/api/bfs/busnessQury/costBalance';
import {queryManageCom} from "@/api/bfs/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_managecom, bfs_debit_and_credit } = toRefs<any>(proxy?.useDict('sys_managecom', 'bfs_debit_and_credit'));
const { bfs_sale_chnl } = toRefs<any>(proxy?.useDict('bfs_sale_chnl'));
const total = ref(0);
const showSearch = ref(true);
const loading = ref(false);
const costBalanceList = 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,
    finItemType: undefined,
    dateRange: undefined,
    costId: undefined,
    saleChnl: undefined,
    riskCode: 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 likeCostName = ref('');
const filteredCostList = ref([]);
const selectCostList = ref([]);

const productList = ref([]);
const filteredProductList = ref([]);
const likeProductName = 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 CostBalanceList(proxy?.addDateRange(queryParams.value, queryParams.value.dateRange));
      costBalanceList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    }
  });
};

/** 查询字典下拉信息 */
const getCache = async () => {
  const res = await getCacheList();
  certificateList.value = res.data.certificateList;
  costList.value = res.data.costList;
  selectCostList.value = res.data.costIdList;
  filteredFinItem.value = certificateList.value;
  filteredSubItem.value = costList.value;
  filteredCostList.value = selectCostList.value;
  productList.value = res.data.productList;
  filteredProductList.value = productList.value;
};

/** 导出按钮操作 */
const handleExport = () => {
  queryParams.value = proxy?.addDateRange(queryParams.value, queryParams.value.dateRange);
  proxy?.download(
    'bfs/bussnessQury/exportCostBalance',
    {
      ...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 filterByCostIdName = () => {
  if (likeCostName.value) {
    filteredCostList.value = selectCostList.value.filter((item) => {
      return item.costId.includes(likeCostName.value) || item.costName.includes(likeCostName.value);
    });
  } else {
    filteredCostList.value = selectCostList.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;
};

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>
