<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" :inline="true" label-width="130px" label-position="left">
            <el-row>
              <el-form-item label="管理机构" prop="manageCom">
                <el-select v-model="queryParams.manageCom" clearable placeholder="请输入管理机构" @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" placeholder="请输入客户账户名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="银行流水号" prop="bankSerialNumber">
                <el-input v-model="queryParams.bankSerialNumber" placeholder="请输入银行流水号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="到账日期" prop="arrivalDate">
                <el-date-picker
                  v-model="dateRange"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleDateRangeChange"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <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.value + '-' + dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="银行记账码" prop="reconciliationCode">
                <el-input v-model="queryParams.reconciliationCode" placeholder="请输入银行记账码" clearable @keyup.enter="handleQuery" />
              </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-row>
            <el-row>
              <el-form-item label="状态" prop="paymentMethod">
                <el-select v-model="queryParams.approvalStatus" clearable placeholder="请输入状态">
                  <el-option v-for="dict in bls_temp_approval_state" :key="dict.value" :label="dict.label" :value="dict.value"></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-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <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" label="id" align="center" prop="id" width="180" show-overflow-tooltip />
        <el-table-column label="管理机构" align="center" prop="manageCom" width="120" 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="temporaryChargeNumber" width="180" show-overflow-tooltip />
        <el-table-column label="进账状态" align="center" prop="approvalStatus" width="100" show-overflow-tooltip>
          <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="paymentMethod" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_rec_method" :value="scope.row.paymentMethod" />
          </template>
        </el-table-column>
        <el-table-column label="客户开户行" align="center" prop="payerBank" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.payerBank" />
          </template>
        </el-table-column>
        <el-table-column label="客户银行账户" align="center" prop="payerBankAccount" width="150" show-overflow-tooltip />
        <el-table-column label="客户账户名称" align="center" prop="payerName" width="150" show-overflow-tooltip />
        <el-table-column label="金额" align="center" prop="amount" width="150" show-overflow-tooltip />
        <el-table-column label="当前使用金额" align="center" prop="useAmount" width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ (scope.row.amount - scope.row.matchingBalance).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="余额" align="center" prop="matchingBalance" width="150" show-overflow-tooltip> </el-table-column>
        <el-table-column label="到账日期" align="center" prop="arrivalDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收款银行账号" align="center" prop="receivingBankAccount" width="200" show-overflow-tooltip />
        <el-table-column label="收款银行名称" align="center" prop="receivingBankName" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.receivingBankName" />
          </template>
        </el-table-column>
        <el-table-column label="对账码" align="center" prop="reconciliationCode" width="150" show-overflow-tooltip />
        <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:information:query']" link type="primary" icon="Edit" @click="handleQury(scope.row)">查看详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :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" readonly />
            </el-form-item>
            <el-form-item v-if="false" label="ID" prop="id">
              <el-input v-model="form.id" readonly />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="form.manageCom" disabled 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" disabled 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="receivingBankAccount">
              <el-input v-model="form.receivingBankAccount" placeholder="请输入收款银行账号" maxlength="100" show-word-limit readonly />
            </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 readonly />
            </el-form-item>
            <el-form-item label="客户开户行" prop="payerBank">
              <el-select v-model="form.payerBank" disabled 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 readonly />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="付款金额" prop="amount">
              <el-input-number v-model="form.amount" placeholder="请输入付款金额" :precision="2" readonly 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
                readonly
              />
            </el-form-item>
            <el-form-item label="到账日期" prop="arrivalDate">
              <el-date-picker
                v-model="form.arrivalDate"
                disabled
                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" disabled 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 readonly />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="缴费项目" prop="chargItems">
              <el-input v-model="form.chargItems" placeholder="请输入缴费项目" readonly />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="是否特殊收费" readonly prop="isSpec">
              <el-switch v-model="form.isSpec" size="large" active-value="Y" inactive-value="N" active-text="是" inactive-text="否" disabled />
            </el-form-item>
            <el-form-item v-if="form.isSpec === 'Y'" label="特殊收费类型" prop="specType" style="margin-left: 140px">
              <el-select v-model="form.specType" disabled 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="请输入备注信息"
                readonly
              >
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-divider content-position="left">信息补录部分</el-divider>
            <el-form-item label="费用类型" prop="cashFlow">
              <el-select v-model="form.cashFlow" placeholder="请输入费用类型">
                <el-option v-for="dict in bls_cash_flow" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="管理机构" prop="costCenter">
              <el-select v-model="form.costCenter" clearable placeholder="请输入管理机构">
                <template #header>
                  <el-input v-model="likeCenterName" placeholder="可根据机构编码或名称模糊查询" @input="filterByCostCenter"></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="taxregno">
              <el-select
                v-model="form.taxregno"
                filterable
                remote
                reserve-keyword
                placeholder="请录入投保单单位名称"
                remote-show-suffix
                :remote-method="remoteGetTaxregno"
                :loading="remoteLoading"
                style="width: 240px"
              >
                <el-option v-for="item in remoteGetTaxregnoList" :key="item.lifnr" :label="item.name1" :value="item.lifnr" />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button v-hasPermi="['bls:information:submit']" type="primary" icon="Position" @click="handleSubmit">信息补录</el-button>
            <el-button type="primary" icon="Close" @click="handleClose">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { parseTime } from '@/utils/ruoyi';
import { ChargesQuery, ChargesVO } from '@/api/bls/charges/types';
import {
  getCharges,
  getCollBank,
  getCostCenter,
  getInformationCharges,
  listCharges,
  listInformationCharges, queryTaxregno,
  submitInformationCharges
} from '@/api/bls/charges';
import { pickerOptions } from '@/utils/date';
import { queryManageComByBranch } from '@/api/bls/cache';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const chargesList = ref<ChargesVO[]>([]);
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 dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const chargesFormRef = ref<ElFormInstance>();
const likeName = ref('');
const filteredManagecom = ref([]);
const manageComCollBank = ref([]);
const ListCollBank = ref([]);
const filteredListCollBank = ref([]);
const likeCollName = ref('');
const sys_managecomCache = ref([]);

const costCenterList = ref([]);
const filteredCenterList = ref([]);
const likeCenterName = ref('');
//供应商信息
const remoteGetTaxregnoList = ref([]);
const remoteLoading=ref(false);

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 { bls_temp_approval_state } = toRefs<any>(proxy?.useDict('bls_temp_approval_state'));
const { bfs_spec_type } = toRefs<any>(proxy?.useDict('bfs_spec_type'));
const { bls_cash_flow } = toRefs<any>(proxy?.useDict('bls_cash_flow'));

const initFormData = {
  id: undefined,
  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,
  cashFlow: undefined,
  costCenter: undefined,
  taxregno: 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,
    reconciliationCode: undefined,
    matchingStatus: undefined,
    matchingBalance: undefined,
    approvalStatus: undefined,
    excessPaymentAmount: undefined,
    manageCom: undefined,
    isEntrust: undefined,
    params: {}
  },
  rules: {
    cashFlow: [{ required: true, message: '费用类型不能为空', trigger: 'blur' }],
    costCenter: [{ required: true, message: '成本中心不能为空', trigger: 'blur' }],
    taxregno: [{ required: true, message: '所属单位不能为空', trigger: 'blur' }]
  }
});
const { form, queryParams, rules } = toRefs(data);

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

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

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

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

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

/** 模糊查询 */
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 initCollBank = async () => {
  const res = await getCollBank();
  if (res.code == 200) {
    ListCollBank.value = res.data;
    filteredListCollBank.value = res.data;
  }
  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 manageComChangeQury = () => {
  if (queryParams.value.manageCom) {
    manageComCollBank.value = ListCollBank.value.filter((item) => {
      return item.manageCom.includes(queryParams.value.manageCom);
    });
    if (manageComCollBank.value.length > 0) {
      filteredListCollBank.value = manageComCollBank.value;
    }
  }
};

// 计算属性用于动态设置 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 reset = () => {
  form.value = { ...initFormData };
  chargesFormRef.value?.resetFields();
};

const handleQury = async (row) => {
  reset();
  const _id = row?.id;
  const res = await getInformationCharges(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '暂收费信息补录';
  loading.value = false;
};
const rowDbclick = (row: any, column: any, event: Event) => {
  loading.value = true;
  handleQury(row);
};

/**
 * 初始化成本中心
 */
const initCostCenter = async () => {
  const res = await getCostCenter();
  if (res.code == 200) {
    costCenterList.value = res.data;
    filteredCenterList.value = res.data;
  }
};

/** 成本中心模糊查询 */
const filterByCostCenter = () => {
  if (likeCenterName.value) {
    filteredCenterList.value = costCenterList.value.filter((item) => {
      return (
        item.accjgName.includes(likeCenterName.value) ||
        item.manageCom.includes(likeCenterName.value) ||
        item.accjgCode.includes(likeCenterName.value)
      );
    });
  } else {
    filteredCenterList.value = costCenterList.value;
  }
};

const handleSubmit = async () => {
  chargesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const res = await submitInformationCharges(form.value);
      if (res.code == 200) {
        proxy.$modal.msgSuccess('提交成功');
        dialog.visible = false;
        reset();
        await getList();
      }
    }
  });
};

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

const getCache = async () => {
  const res = await queryManageComByBranch();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};
const remoteGetTaxregno = async (query: string) => {
  if (query) {
    remoteLoading.value = true;
    const res = await queryTaxregno(query);
    remoteLoading.value = false;
    if (res.code == 200) {
      remoteGetTaxregnoList.value = res.data;
    }
  } else {
    remoteGetTaxregnoList.value = [];
  }
};

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

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