<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" @submit.prevent="handleQuery" :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>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @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">
          <right-toolbar :show-add="checkPermi(['bill:bill:add'])" :show-edit="false" :show-delete="false" @update:add="handleAdd"></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="billName" />
        <el-table-column label="收费范围" align="center" prop="chargeScope" width="100">
          <template #default="scope">
            <template v-if="ShowHouseList.includes(scope.row.chargeTypeId)">
              <DictTag :options="com_bill_charge_scope_house" :value="scope.row.chargeScope"></DictTag>
            </template>
            <template v-else>
              <DictTag :options="com_questionnaire_scope" :value="scope.row.chargeScope"></DictTag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="收费项目" align="center" prop="chargeItemName" />
        <el-table-column label="起止时间" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}/{m}/{d}') }}</span> -
            <span>{{ parseTime(scope.row.endDate, '{y}/{m}/{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" width="180">
          <template #default="scope">
            <div class="flex justify-center" v-if="scope.row.unit">
              <span>{{ scope.row.fixedPrice }}</span> /
              <DictTag :options="com_charge_item_unit" :value="scope.row.unit"></DictTag>
            </div>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleChange(scope.row)">生成账单</el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-has-permi="['bill:bill:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleMain(scope.row)" v-has-permi="['bill:bill:query']">详情</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>
    <el-dialog v-model="BillVisible" :title="BillForm.title" width="500">
      <el-form v-loading="UploadLoading" :model="BillForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="账单生成时间">
          <el-date-picker
            v-if="BillForm.chargePeriod === '0'"
            v-model="BillForm.years"
            type="years"
            format="YYYY"
            value-format="YYYY"
            placeholder="选择账单生成年份"
            style="width: 100%"
          />
          <!--          滚动月份 -->
          <el-date-picker
            format="YYYY-MM"
            value-format="YYYY-MM"
            v-else-if="BillForm.chargePeriod === '1'"
            v-model="BillForm.yearMonths"
            :disabled-date="handleDisableMonth"
            type="months"
            placeholder="选择账单生成月份"
            style="width: 100%"
          />
          <!--          滚动季度 -->
          <el-date-picker
            format="YYYY-MM"
            value-format="YYYY-MM"
            v-else-if="BillForm.chargePeriod === '3'"
            v-model="BillForm.yearQuarters"
            type="months"
            placeholder="选择账单生成季度"
            :disabled-date="handleDisableMonth"
            style="width: 100%"
          />
          <el-date-picker
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            v-else-if="BillForm.chargePeriod === '2'"
            v-model="BillForm.days"
            :disabled-date="handleDisableMonth"
            type="dates"
            placeholder="选择日期生成每日账单"
            style="width: 100%"
          />

          <!--          季度账单-滚动季度 -->
          <!--          <QuarterSelect v-if="BillForm.chargePeriod === '3' && BillForm.periodCalcType === '1'" v-model="myQuarter" @change="onQuarterChange" />-->
        </el-form-item>
        <!--        <el-form-item label="选择生成账单的房屋">-->
        <!--          <div class="flex flex-col">-->
        <!--            <div>-->
        <!--              <el-radio-group v-model="BillForm.chargeScope">-->
        <!--                <el-radio v-for="(item, index) in com_bill_charge_scope_house" :key="index" :value="item.value" :label="item.label"></el-radio>-->
        <!--              </el-radio-group>-->
        <!--              <div style="height: 32px" v-if="BillForm.chargeScope === '1'">-->
        <!--                <el-button @click="OpenUseTablesFun" link type="primary" class="ml-10px">请选择房屋</el-button>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item v-if="BillForm.chargeScope === '1'">-->
        <!--          <div class="residentBox">-->
        <!--            <House returnvalue="houseId" ref="HolderRef" :isMultiple="true" @change="handleSelect"> </House>-->
        <!--          </div>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="BillVisible = false">关闭</el-button>
          <el-button :loading="UploadLoading" type="primary" @click="handleChangeApi"> 生成 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bill" lang="ts">
import PageHeader from '@/components/Pageheader/index.vue';
import pagination from '@/components/Pagination/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import { listBill, manualGenerateApi } from '@/api/system/SdbBill';
import { BillVO, BillQuery, BillForm } from '@/api/system/SdbBill/type';
import { listChargeItem } from '@/api/system/SdbChargeItem';
import { checkPermi } from '@/utils/permission';
import { ref } from 'vue';

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

const billList = ref<BillVO[]>([]);
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 ShowHouseList = ['2064181187503652865', '2049026503017136129'];

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

const { queryParams } = toRefs(data);

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

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

/** 搜索按钮操作 */
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 = (row?: BillVO) => {
  router.push({
    path: '/sdb/editSdbbill',
    query: {
      id: row.id
    }
  });
};
// 详情
function handleMain(row: BillVO) {
  router.push({
    path: '/sdb/sdbbillMain',
    query: {
      id: row.id
    }
  });
}
// 删除
// function handleDelete(row: BillVO) {
//   delBill(row.id).then((res) => {
//     ElMessage.success(res.msg);
//     getList();
//   })
// }
const BillVisible = ref(false);
const BillForm = ref<{
  title: string;
  billId: string;
  /**
   * 收费周期 0年 1月 2日 3 季度 4永久；为空时取账单配置
   */
  chargePeriod: string;
  chargeScope: string;
  yearMonths?: string[];
  days?: string[];
  periodCalcType: string;
  houseId: string[];
  yearQuarters?: string[];
  years?: string[];
  startDate?: string;
  endDate?: string;
}>({
  title: '',
  billId: '',
  chargePeriod: '1', // 账单类型
  chargeScope: '0',
  periodCalcType: '0',
  houseId: []
});
// const HolderRef = ref<InstanceType<typeof House>>();
// // 打开模态框
// function OpenUseTablesFun() {
//   HolderRef.value.open(BillForm.value.houseId);
// }
// // 接受选择的房屋id
// function handleSelect(val: string[]) {
//   BillForm.value.houseId = val;
// }
// 生成账单
function handleChange(row: BillVO) {
  clearChangeBillForm();
  BillVisible.value = true;
  BillForm.value.title = row.billName;
  BillForm.value.chargePeriod = row.chargePeriod;
  BillForm.value.billId = row.id;
  BillForm.value.periodCalcType = row.periodCalcType;
  BillForm.value.startDate = row.startDate;
  BillForm.value.endDate = row.endDate;
  if (BillForm.value.chargePeriod === '1') {
    BillForm.value['yearMonths'] = [];
  } else if (BillForm.value.chargePeriod === '3') {
    BillForm.value['yearQuarters'] = [];
  } else if (BillForm.value.chargePeriod === '0') {
    BillForm.value['year'] = [];
  }
}

const UploadLoading = ref(false);
// 生成账单
function handleChangeApi() {
  UploadLoading.value = true;
  manualGenerateApi(BillForm.value)
    .then((res) => {
      ElMessage.success(res.msg);
      clearChangeBillForm();
      BillVisible.value = false;
    })
    .finally(() => {
      UploadLoading.value = false;
    });
}
// 清空表单
function clearChangeBillForm() {
  BillForm.value = {
    periodCalcType: undefined,
    title: '',
    billId: '',
    chargePeriod: '1',
    chargeScope: '0',
    houseId: []
  };
}
// 禁用月份
function handleDisableMonth(date: Date) {
  if (!BillForm.value.startDate || !BillForm.value.endDate) return false;
  return date.getTime() > new Date(BillForm.value.endDate).getTime();
}

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

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