<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" :inline="true" :model="queryParams" :rules="rules" label-position="left" label-width="130px">
            <el-row>
              <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="arrivalDate">
                <el-date-picker
                  v-model="dateRange"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  @change="handleDateRangeChange"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="数据来源" prop="fromSystem">
                <el-select v-model="queryParams.fromSystem" clearable placeholder="请输入数据来源">
                  <el-option
                    v-for="dict in sys_from_system"
                    :key="dict.value"
                    :label="dict.value + '-' + dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付费类型" prop="payeeType">
                <el-select v-model="queryParams.payeeType" clearable placeholder="请输入付费类型">
                  <el-option
                    v-for="dict in sys_pay_method"
                    :key="dict.value"
                    :label="dict.value + '-' + dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
  </div>
  <el-card shadow="hover">
    <el-table v-loading="loading" :data="monitoringList">
      <el-table-column label="管理机构" align="center" prop="manageCom" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="sys_managecom" :value="scope.row.manageCom" />
        </template>
      </el-table-column>
      <el-table-column label="数据来源" align="center" prop="fromSystem" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
        </template>
      </el-table-column>
      <el-table-column label="付费类型" align="center" prop="payeeType" width="120" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="sys_pay_method" :value="scope.row.payeeType" />
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="amount" show-overflow-tooltip> </el-table-column>
    </el-table>
    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />

    <el-form ref="monitoringFormRef" :inline="true" :model="monitoringForm" label-position="left" label-width="130px" style="margin-top: 20px">
      <el-form-item label="总金额" prop="totlAmount">
        <el-input v-model="monitoringForm.totlAmount" disabled />
      </el-form-item>
    </el-form>

    <el-row style="margin-top: 20px">
      <el-button v-hasPermi="['bls:monitoring:export']" type="success" icon="Download" @click="handleExport">导出数据</el-button>
    </el-row>
  </el-card>
</template>
<script setup name="Monitoring" lang="ts">
import { queryImonitoringList } from '@/api/bls/monitoring';
import {queryManageCom} from "@/api/bls/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_pay_method } = toRefs<any>(proxy?.useDict('sys_pay_method'));
const showSearch = ref(true);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const monitoringFormRef = ref<ElFormInstance>();
const total = ref(0);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 30,
    manageCom: undefined,
    arrivalDate: undefined,
    fromSystem: undefined,
    payeeType: undefined
  },
  rules: {
    manageCom: [{ required: true, message: '管理机构不能为空', trigger: 'blur' }]
  }
});
const { queryParams, rules } = toRefs(data);
const loading = ref(false);
const monitoringList = ref([]);
const monitoringData = reactive({
  monitoringForm: {
    totlAmount: undefined
  }
});
const { monitoringForm } = toRefs(monitoringData);
const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);

const handleQuery = () => {
  queryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (dateRange.value[0] === '' || dateRange.value[1] === '') {
        proxy.$modal.msgError('请录入转账日期');
      } else {
        reset();
        await getList();
      }
    }
  });
};

const getList = async () => {
  const res = await queryImonitoringList(proxy?.addDateRange(queryParams.value, dateRange.value));
  monitoringList.value = res.rows;
  total.value = res.total;
  monitoringForm.value.totlAmount = res.otherMsg.totlAmount;
};

const reset = () => {
  monitoringList.value = [];
  monitoringForm.value.totlAmount = undefined;
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRange.value = ['', ''];
};

const handleExport = () => {
  if (queryParams.value.manageCom === undefined) {
    proxy.$modal.msgError('请选择管理机构');
    return;
  }
  if (dateRange.value[0] === '' || dateRange.value[1] === '') {
    proxy.$modal.msgError('请录入转账日期');
    return;
  }
  proxy?.download(
    'bls/monitoring/export',
    {
      ...queryParams.value
    },
    `流动监测_${new Date().getTime()}.xlsx`
  );
};

// 计算属性用于动态设置 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('结束日期不能超过开始日期一年以上');
    dateRange.value = ['', ''];
  }
};

/** 模糊查询 */
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 getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};
onMounted(() => {
  getCache();
});
</script>

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