<template>
  <div class="p-2 h-full flex flex-col">
    <pageheader></pageheader>
    <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" :inline="true">
            <el-form-item label="收费项目" prop="chargeItemId">
              <el-select v-model="queryParams.chargeItemId" placeholder="请选择收费项目">
                <el-option v-for="(item, index) in chargeItems" :key="index" :value="item.id" :label="item.itemName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="精确查询" prop="type">
              <el-select style="width: 150px; margin-right: 10px" v-model="queryParams.type">
                <el-option v-for="(item, index) in com_bill_search_filter" :key="index" :value="item.value" :label="item.label"></el-option>
              </el-select>
              <el-input v-model="queryParams.billCode" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card class="flex-1" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleMain" v-hasPermi="['system:bill:add']">新增</el-button>
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:bill:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:bill:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:bill:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="billList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="账单编号" align="center" prop="billCode" />
        <el-table-column label="账单名称" align="center" prop="billCode" />
        <el-table-column label="收费范围" align="center" prop="chargeScope">
          <template #default="scope">
            <dict-tag :options="com_questionnaire_scope" :value="scope.row.chargeScope"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="收费项目" align="center" prop="chargeItemId" />
        <el-table-column label="收费周期" align="center" prop="chargePeriod">
          <template #default="scope">
            <dict-tag :options="com_bill_charge_period" :value="scope.row.chargePeriod"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束日期" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="chargePeriod" />
        <el-table-column label="费用合计" align="center" prop="chargePeriod" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:bill:edit']">修改</el-button>
            <el-button link type="primary" icon="Edit" @click="handleMain(scope.row)" v-hasPermi="['system:bill:edit']">详情</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:bill:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Bill" lang="ts">
import { listBill, getBill, delBill, addBill, updateBill } from '@/api/system/SdbBill/index';
import { BillVO, BillQuery, BillForm } from '@/api/system/SdbBill/type';
import { listChargeItem } from '@/api/system/SdbChargeItem';

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

const billList = ref<BillVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const billFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BillForm = {
  id: undefined,
  billCode: undefined,
  chargeItemId: undefined,
  chargeScope: undefined,
  chargePeriod: undefined,
  startDate: undefined,
  endDate: undefined,
  villageId: undefined,
  remark: undefined,
  cerateTime: undefined
};
const data = reactive<PageData<BillForm, BillQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    billCode: '',
    type: '',
    value: ''
  }
});

const { queryParams, form } = toRefs(data);

const chargeItems = ref([]);
function init() {
  listChargeItem().then((res) => {
    chargeItems.value = res.rows;
  });
}
init();

/** 查询账单管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBill(queryParams.value);
  billList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  billFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: BillVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const router = useRouter();
/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/sdb/addSdbbill'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BillVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getBill(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改账单管理';
};

/** 提交按钮 */
const submitForm = () => {
  billFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBill(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addBill(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

function handleMain(row) {
  router.push({
    path: '/sdb/sdbbillMain',
    query: {
      id: row.id
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BillVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除账单管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delBill(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/bill/export',
    {
      ...queryParams.value
    },
    `bill_${new Date().getTime()}.xlsx`
  );
};

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

<style lang="scss" scoped>
.el-table {
  height: calc(100% - 80px);
}
</style>
