<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" label-position="left" label-width="130px">
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="queryParams.manageCom" placeholder="请输入管理机构" clearable @change="manageComChangeQury">
                <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="receivingBankAccount">
              <el-select v-model="queryParams.receivingBankAccount" clearable placeholder="请输入收款银行账号">
                <template #header>
                  <el-input v-model="likeCollName" placeholder="可根据银行账号模糊查询" @input="filterByCollBankName"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredListCollBank"
                  :key="dict.bankAccount"
                  :label="dict.bankAccount"
                  :value="dict.bankAccount"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户账户名称" prop="payerName">
              <el-input
                v-model="queryParams.payerName"
                clearable
                placeholder="请输入客户账户名称"
                maxlength="100"
                show-word-limit
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="虚拟户编码" prop="virtualAccount">
              <el-input
                v-model="queryParams.virtualAccount"
                clearable
                placeholder="请输入虚拟户编码"
                maxlength="50"
                show-word-limit
                @keyup.enter="handleQuery"
              />
            </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"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select v-model="queryParams.paymentMethod" clearable placeholder="请输入缴费方式">
                <el-option v-for="dict in sys_rec_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否委托专户" prop="isEntrust">
              <el-select v-model="queryParams.isEntrust" clearable placeholder="是否委托专户">
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="特殊收费类型" prop="specType">
              <el-select v-model="queryParams.specType" clearable placeholder="特殊收费类型">
                <el-option v-for="dict in bfs_spec_type" :key="dict.value" :label="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-row>
          </el-form>
        </el-card>
      </div>
    </transition>
  </div>
  <el-card shadow="never">
    <template #header>
      <el-row :gutter="10" class="mb8">
        <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
      </el-row>
    </template>
    <el-table v-loading="loading" :data="chargesList" @row-dblclick="rowDbclick">
      <el-table-column v-if="false" align="center" label="id" prop="temporaryChargeId" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="对账码" prop="reconciliationCode" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="虚拟户编码" prop="virtualAccount" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="客户账户名称" prop="payerName" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="客户开户行" prop="payerBank" show-overflow-tooltip width="120">
        <template #default="scope">
          <dict-tag :options="sys_bank_code" :value="scope.row.payerBank" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="付款人银行账号" prop="payerBankAccount" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="是否委托专户" prop="isEntrust" show-overflow-tooltip width="120">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isEntrust" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="金额" prop="amount" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="匹配余额" prop="matchingBalance" show-overflow-tooltip width="150" />
      <el-table-column align="center" label="收款银行账号" prop="receivingBankAccount" show-overflow-tooltip width="200" />
      <el-table-column align="center" label="收款银行名称" prop="receivingBankName" show-overflow-tooltip width="120">
        <template #default="scope">
          <dict-tag :options="sys_bank_code" :value="scope.row.receivingBankName" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="到账日期" prop="arrivalDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="申请状态" prop="approvalStatus">
        <template #default="scope">
          <dict-tag :options="bls_temp_approval_state" :value="scope.row.approvalStatus" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip width="350" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button
              v-hasPermi="['bls:charges:canlcel']"
              link
              type="primary"
              icon="Edit"
              :disabled="isButtonDisabled(scope.row)"
              @click="handleQury(scope.row)"
              >查看详情</el-button
            >
          </el-tooltip>
        </template>
      </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-card>

  <!--TODO 将4个界面的弹出部分抽离出来，做成公共的dialog -->
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="90%" top="5vh" append-to-body class="scrollbar">
    <el-card shadow="hover">
      <el-form ref="chargesFormRef" :model="form" :rules="rules" :inline="true" label-width="130px" label-position="left">
        <!-- 隐藏信息 -->
        <el-row>
          <el-form-item v-if="false" label="暂收费ID" prop="temporaryChargeId">
            <el-input v-model="form.temporaryChargeId" clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="管理机构" prop="manageCom">
            <el-select v-model="form.manageCom" clearable placeholder="请输入管理机构">
              <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否委托专户" prop="isEntrust">
            <el-select v-model="form.isEntrust" clearable placeholder="是否委托专户" @change="isEntrustForm">
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收款银行账号" prop="receivingBankAccount">
            <el-input v-model="form.receivingBankAccount" placeholder="请输入收款银行账号" maxlength="100" show-word-limit clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="客户账户名称" prop="payerName">
            <el-input v-model="form.payerName" placeholder="请输入客户账户名称" maxlength="100" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="客户开户行" prop="payerBank">
            <el-select v-model="form.payerBank" clearable placeholder="请输入客户开户行">
              <el-option v-for="dict in sys_bank_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户银行账户" prop="payerBankAccount">
            <el-input v-model="form.payerBankAccount" placeholder="请输入客户银行账户" maxlength="50" show-word-limit clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="付款金额" prop="amount">
            <el-input-number v-model="form.amount" placeholder="请输入付款金额" :precision="2" clearable style="width: 230px" />
          </el-form-item>
          <el-form-item label="虚拟户编码" prop="virtualAccount" style="margin-left: 10px">
            <el-input v-model="form.virtualAccount" placeholder="请输入虚拟户编码" maxlength="6" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="到账日期" prop="arrivalDate">
            <el-date-picker
              v-model="form.arrivalDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择过期时间"
              style="width: 240px"
              :disabled-date="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="缴费方式" prop="paymentMethod">
            <el-select v-model="form.paymentMethod" clearable placeholder="请输入缴费方式">
              <el-option
                v-for="dict in sys_rec_method.filter((dict) => dict.value !== '01')"
                :key="dict.value"
                :label="dict.value + '-' + dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="银行记账码" prop="reconciliationCode">
            <el-input v-model="form.reconciliationCode" placeholder="请输入银行记账码" maxlength="50" disabled show-word-limit clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="缴费项目" prop="chargItems">
            <el-input v-model="form.chargItems" placeholder="请输入缴费项目" clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="是否特殊收费" clearable prop="isSpec">
            <el-switch
              v-model="form.isSpec"
              size="large"
              active-value="Y"
              inactive-value="N"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
          <el-form-item v-if="form.isSpec === 'Y'" label="特殊收费类型" prop="specType" style="margin-left: 140px">
            <el-select v-model="form.specType" placeholder="特殊收费类型">
              <el-option v-for="dict in bfs_spec_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              :rows="4"
              style="width: 440px"
              type="textarea"
              maxlength="500"
              show-word-limit
              placeholder="请输入备注信息"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-button
            v-hasPermi="['bls:charges:canlcel']"
            type="primary"
            icon="Position"
            @click="handleCancel"
          >作废</el-button
          >
          <el-button
            type="primary"
            icon="Close"
            @click="handleClose"
          >关闭</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </el-dialog>


</template>
<script setup name="ChargesCancal" lang="ts">
import {chargesCancel, getCharges, getCollBank, listCanelCharges, listCharges} from '@/api/bls/charges';
import {pickerOptions} from "@/utils/date";
import {co} from "~/dist/assets/index-Bp8MX3GU";
import {queryManageCom} from "@/api/bls/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const chargesList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const likeName = ref('');
const filteredManagecom = ref([]);
const likeCollName = ref('');
const filteredListCollBank = ref([]);
const manageComCollBank = ref([]);
const ListCollBank = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { receiv_bank_accno } = toRefs<any>(proxy?.useDict('receiv_bank_accno'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const { sys_rec_method } = toRefs<any>(proxy?.useDict('sys_rec_method'));
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));
const { bfs_spec_type } = toRefs<any>(proxy?.useDict('bfs_spec_type'));
const { bls_temp_approval_state } = toRefs<any>(proxy?.useDict('bls_temp_approval_state'));

const initFormData = {
  temporaryChargeId: undefined,
  manageCom: undefined,
  temporaryChargeNumber: undefined,
  bankSerialNumber: undefined,
  payerName: undefined,
  payerBank: undefined,
  payerBankAccount: undefined,
  amount: undefined,
  paymentMethod: undefined,
  receivingBankAccount: undefined,
  receivingBankName: undefined,
  arrivalDate: undefined,
  reconciliationCode: undefined,
  matchingStatus: undefined,
  matchingBalance: undefined,
  approvalStatus: undefined,
  excessPaymentAmount: undefined,
  virtualAccount: undefined,
  isEntrust: undefined,
  remark: undefined,
  isSpec: undefined,
  specType: undefined,
  chargItems: undefined
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    temporaryChargeNumber: undefined,
    bankSerialNumber: undefined,
    payerName: undefined,
    payerBank: undefined,
    payerBankAccount: undefined,
    amount: undefined,
    paymentMethod: undefined,
    receivingBankAccount: undefined,
    receivingBankName: undefined,
    arrivalDate: undefined,
    matchingStatus: undefined,
    matchingBalance: undefined,
    //审批状态为审批通过
    approvalStatus: '1',
    excessPaymentAmount: undefined,
    manageCom: undefined,
    isEntrust: undefined,
    isSpec: undefined,
    specType: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const chargesFormRef = ref<ElFormInstance>();

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

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

/**
 * 初始化银行列表
 */
const initCollBank = async () => {
  const res = await getCollBank();
  if (res.code == 200) {
    ListCollBank.value = res.data;
    filteredListCollBank.value = res.data;
    manageComCollBank.value = res.data;
  }
  filteredManagecom.value = sys_managecomCache.value;
};

/** 查询团体暂收费列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCanelCharges(proxy?.addDateRange(queryParams.value, dateRange.value));
  chargesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleCancel = async () => {
  await proxy?.$modal.confirm('确定要作废客户' + form.value.payerName + '的暂收费吗？');
  loading.value = true;
  try {
    const res = await chargesCancel(form.value);
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('作废成功');
    }
    dialog.visible = false;
  } finally {
    loading.value = false;
  }

  await getList();
};

const isButtonDisabled = (row) => {
  // 根据row的状态或其他条件来决定按钮是否禁用
  return row.amount !== row.matchingBalance;
};

const manageComChangeQury = () => {
  queryParams.value.receivingBankAccount = undefined;
  if (queryParams.value.manageCom) {
    let _manageCom = '86';
    if (queryParams.value.manageCom.length >= 4) {
      _manageCom = queryParams.value.manageCom.slice(0, 4);
    }
    manageComCollBank.value = ListCollBank.value.filter((item) => {
      return item.manageCom.includes(_manageCom);
    });
    filteredListCollBank.value = manageComCollBank.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 filterByCollBankName = () => {
  if (manageComCollBank.value === ListCollBank.value) {
    if (likeCollName.value) {
      filteredListCollBank.value = ListCollBank.value.filter((item) => {
        return item.bankAccount.includes(likeCollName.value);
      });
    } else {
      filteredListCollBank.value = ListCollBank.value;
    }
  } else {
    if (likeCollName.value) {
      filteredListCollBank.value = manageComCollBank.value.filter((item) => {
        return item.bankAccount.includes(likeCollName.value);
      });
    } else {
      filteredListCollBank.value = manageComCollBank.value;
    }
  }
};

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

const handleQury = async (row) => {
  reset();
  const _id = row?.temporaryChargeId;
  const res = await getCharges(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '暂收费作废';
  loading.value = false;
};

const handleClose = () => {
  reset();
  dialog.visible = false;
};

const rowDbclick = (row: any, column: any, event: Event) => {
  loading.value = true;
  handleQury(row);
};

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

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

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