<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" label-width="100px" :inline="true">
            <el-form-item label="凭证类型编号" prop="certificateId">
              <el-input v-model="queryParams.certificateId" placeholder="请输入凭证类型编号" />
            </el-form-item>
            <el-form-item label="凭证类型名称" prop="certificateName">
              <el-input v-model="queryParams.certificateName" placeholder="请输入凭证类型名称" />
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['bfs:costTypeDef:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="costTypeDefList">
        <el-table-column label="凭证类型编号" align="center" prop="certificateId" />
        <el-table-column label="费用类型编码" align="center" prop="costId" width="150px" />
        <el-table-column label="费用类型名称" align="center" prop="costName" width="150px" show-overflow-tooltip />
        <el-table-column label="借贷标志" align="center" prop="finItemType">
          <template #default="scope">
            <dict-tag :options="bfs_debit_and_credit" :value="scope.row.finItemType" />
          </template>
        </el-table-column>
        <el-table-column label="科目类型编码" align="center" prop="finItemCode" width="150px" />
        <el-table-column label="科目类型名称" align="center" prop="finItemName" width="150px" show-overflow-tooltip />
        <el-table-column label="费用类型描述" align="center" prop="remark" width="110px" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="sys_yesno_valid" :value="scope.row.state" />
          </template>
<!--          <template #default="scope">-->
<!--            <el-switch-->
<!--              v-model="scope.row.state"-->
<!--              active-value="Y"-->
<!--              inactive-value="N"-->
<!--              inline-prompt-->
<!--              active-text="有效"-->
<!--              inactive-text="无效"-->
<!--              @change="handleStatusChange(scope.row)"-->
<!--            ></el-switch>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['bfs:costTypeDef:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="凭证提取定义" placement="top">
              <el-button v-hasPermi="['bfs:elementsMapping:look']" link type="primary" icon="Compass" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
      <el-form ref="costTypeDefFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="凭证类型编号" prop="certificateId">
              <el-input v-model="form.certificateId" placeholder="请输入凭证类型编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用类型编码" prop="costId">
              <el-input v-model="form.costId" placeholder="请输入费用类型编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="费用类型名称" prop="costName">
              <el-input v-model="form.costName" placeholder="请输入费用类型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借贷标记" prop="finItemType">
              <el-select v-model="form.finItemType" placeholder="借贷标记" clearable>
                <el-option v-for="dict in bfs_debit_and_credit" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="科目类型编码" prop="finItemCode">
              <el-select v-model="form.finItemCode" clearable collapse-tags :max-collapse-tags="1" @change="finItemCodeSelected">
                <template #header>
                  <el-input v-model="likeFinItemName" placeholder="可根据模版名称模糊查询" @input="filterByFinItemName"></el-input>
                </template>
                <el-option
                  v-for="item in findFinItemList"
                  :key="item.finItemCode"
                  :label="item.finItemCode + '-' + item.finItemName"
                  :value="item.finItemCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科目类型名称" prop="finItemName">
              <el-input v-model="form.finItemName" placeholder="请输入科目类型名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="科目明细" prop="subItemCode">
              <el-select v-model="form.subItemCode" clearable collapse-tags :max-collapse-tags="1" @change="finSubCodeSelected">
                <template #header>
                  <el-input v-model="likeSubItemName" placeholder="可根据模版名称模糊查询" @input="filterBySubItemName"></el-input>
                </template>
                <el-option
                  v-for="item in findSubItemList"
                  :key="item.subItemCode"
                  :label="item.subItemCode + '-' + item.subItemName"
                  :value="item.subItemCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-switch v-model="form.state" active-value="Y" inactive-value="N" inline-prompt active-text="有效" inactive-text="无效"></el-switch>
              <!--              <el-input v-model="form.status" placeholder="请输入科目类型名称" />-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="费用类型描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入费用类型描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <cost-type-drawer
      v-model:visible="isExecution"
      :cost-id="CostId"
      :fin-item-code="FinItemCode"
      :fin-item-type="FinItemType"
      :fin-data="FinData"
      :certificate-id="queryParams.certificateId"
    />
  </div>
</template>

<script setup name="FiCostTypeDefDialog" lang="ts">
import { CostTypeDefForm, CostTypeDefQuery, CostTypeDefVO } from '@/api/bfs/fiCertificateType/costType';
import { addCostTypeDef, changeCostTypeStatus, getCostTypeDef, getCostTypeDefList, updateCostTypeDef } from '@/api/bfs/fiCertificateType';
import { RouteLocationNormalized } from 'vue-router';
import { getFinItemDict } from '@/api/bfs/finItemDef';
import CostTypeDrawer from '@/views/bfs/fiCertificateType/CostTypeDrawer.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const { bfs_debit_and_credit, bfs_finiterm_state, sys_yesno_valid } = toRefs<any>(
  proxy?.useDict('bfs_debit_and_credit', 'bfs_finiterm_state', 'sys_yesno_valid')
);
const showSearch = ref(true);
const loading = ref(true);
const costTypeDefList = ref<CostTypeDefVO[]>([]);
const total = ref(0);
const costTypeDefFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const finItemList = ref([]);
const findFinItemList = ref([]);
const likeFinItemName = ref('');

const subItemList = ref([]);
const findSubItemList = ref([]);
const likeSubItemName = ref('');

const CostId = ref('');
const FinItemType = ref('');
const FinItemCode = ref('');
const isExecution = ref(false);
const FinData = ref({});

const initFormData: CostTypeDefForm = {
  certificateId: undefined,
  costId: undefined,
  costName: undefined,
  finItemType: undefined,
  finItemCode: undefined,
  finItemName: undefined,
  remark: undefined
};
const data = reactive<PageData<CostTypeDefForm, CostTypeDefQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    certificateId: undefined,
    certificateName: undefined,
    params: {}
  },
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);

const quryCostTypeDef = (certificateId) => {
  loading.value = true;
  getCostTypeDefList(certificateId).then((res) => {
    costTypeDefList.value = res.data;
    loading.value = false;
  });
};
const getCertificateId = async (CertificateId, CertificateName) => {
  queryParams.value.certificateId = CertificateId.toString();
  queryParams.value.certificateName = CertificateName.toString();
  form.value.certificateId = queryParams.value.certificateId;
  await quryCostTypeDef(queryParams.value.certificateId);
};

/** 关闭按钮 */
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/bfs/config/ficertificatetype'
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加费用类型定义';
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  form.value.certificateId = queryParams.value.certificateId;
  costTypeDefFormRef.value?.resetFields();
};
/** 查询科目信息字典 */
const getFinItem = () => {
  getFinItemDict().then((res) => {
    finItemList.value = res.data.finItem;
    findFinItemList.value = res.data.finItem;
    subItemList.value = res.data.subItem;
    findSubItemList.value = res.data.subItem;
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CostTypeDefVO) => {
  reset();
  const _id = row?.id;
  const res = await getCostTypeDef(_id);
  Object.assign(form.value, res.data);
  //更新明细科目下拉内容
  filterBySubItemName();
  dialog.visible = true;
  dialog.title = '修改凭证类型定义';
};

const handleDetail = (row?: CostTypeDefVO) => {
  CostId.value = row.costId;
  FinItemType.value = row.finItemType;
  FinItemCode.value = row.finItemCode;
  FinData.value = {
    certificateId: queryParams.value.certificateId,
    costId: row.costId,
    finItemType: row.finItemType,
    finItemCode: row.finItemCode,
    subItemCode: row.subItemCode
  };
  isExecution.value = true;
};

const finItemCodeSelected = (val: any) => {
  const finItem = finItemList.value.find((item) => item.finItemCode === val);
  form.value.finItemCode = finItem?.finItemCode;
  form.value.finItemName = finItem?.finItemName;
  //更新明细科目下拉内容
  filterBySubItemName();
};

const finSubCodeSelected = (val: any) => {
  const subItem = subItemList.value.find((item) => item.subItemCode === val);
  form.value.subItemCode = subItem?.subItemCode;
};

const handleStatusChange = async (row: CostTypeDefVO) => {
  let text = row.state === 'Y' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.costName + '"费用类型吗?');
    await changeCostTypeStatus(row.id, row.state);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.state = row.state === 'Y' ? 'N' : 'Y';
  }
};

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

/** 提交按钮 */
const submitForm = () => {
  costTypeDefFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await updateCostTypeDef(form.value);
      } else {
        await addCostTypeDef(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await loadPage();
    }
  });
};

/**
 * 科目编码模糊查询
 */
const filterByFinItemName = () => {
  if (likeFinItemName.value) {
    findFinItemList.value = finItemList.value.filter(
      (item) => item.finItemName.includes(likeFinItemName.value) || item.finItemCode.includes(likeFinItemName.value)
    );
  } else {
    findFinItemList.value = finItemList.value;
  }
};

/**
 * 科目明细模糊匹配
 */
const filterBySubItemName = () => {
  // 如果没有选择科目代码，直接清空结果并返回
  if (!form.value.finItemCode) {
    findSubItemList.value = [];
    return;
  }
  if (likeSubItemName.value) {
    findSubItemList.value = subItemList.value.filter(
      (item) =>
        (item.finItemCode === form.value.finItemCode && item.subItemName.includes(likeSubItemName.value)) ||
        (item.finItemCode === form.value.finItemCode && item.subItemName.includes(likeSubItemName.value))
    );
  } else {
    findSubItemList.value = subItemList.value.filter((item) => item.finItemCode === form.value.finItemCode);
  }
};

const loadPage = () => {
  getCertificateId(route.query.certificateId, route.query.certificateName);
  getFinItem();
};

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

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