<template>
  <div class="p-2">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" :draggable="draggable">
      <el-form ref="formRef" :inline="true" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="补助名称" prop="subsidyName">
          <el-input v-model="formData.subsidyName" placeholder="请输入补助名称" />
        </el-form-item>
        <el-form-item label="补助类型" prop="subsidyType">
          <el-select v-model="formData.subsidyType" placeholder="请选择补助类型">
            <el-option
                v-for="dict in SUBTYPE"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补助金额" prop="fillMoney">
          <el-input v-model="formData.fillMoney" placeholder="请输入补助金额" />
        </el-form-item>
        <el-form-item label="预计到账时间" prop="fillDate" label-width="108px">
          <el-date-picker v-model="formData.fillDate" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择预计到账时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入账钱包" prop="bagCode">
          <el-select v-model="formData.bagCode" placeholder="请选择入账钱包">
            <el-option
                v-for="dict in CARDBAGTYPE"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补助说明" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入补助说明" />
        </el-form-item>
      </el-form>
      <el-divider/>

      <el-form ref="queryFormRef" :model="itemQuery" :inline="true" label-width="68px" class="-mb-15px">
          <el-form-item label="人员名称" prop="realName">
            <el-input v-model="itemQuery.realName" placeholder="请输入人员姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="itemQuery.deptName" placeholder="请输入部门姓名" clearable style="width: 240px" @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-item>
            <el-button v-if="visible" v-hasPermi="['subsidy:ptSubsidy:add']" type="primary" plain icon="Plus" @click="openWindowDailog()">新增</el-button>
            <el-button v-if="visible" v-hasPermi="['subsidy:ptSubsidy:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-form-item>
      </el-form>

      <br><br>
      <el-table v-loading="loading" :data="formData.ptSubsidyItemList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="35" align="center" />
        <el-table-column type="index" width="50" label="序号"/>
        <el-table-column v-if="false" label="ID" align="center" prop="itemId" />
        <el-table-column v-if="false" label="mainId" align="center" prop="mainId" />
        <el-table-column label="工号" align="center" prop="userNumb" />
        <el-table-column label="姓名" align="center" prop="realName" />
        <el-table-column label="部门" align="center" prop="deptName" />
        <el-table-column label="补助金额" align="center" prop="fillMoney" />
        <el-table-column label="到账日期" align="center" prop="fillDate" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.fillDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 翻页组件 -->
      <pagination v-show="total > 0" v-model:page="itemQuery.pageNum" v-model:limit="itemQuery.pageSize" :total="total" @pagination="getList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="visible" :loading="formLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <user-account-select ref="userAccountSelect" @success="selectUser"></user-account-select>
  </div>
</template>

<script setup name="PtSubsidyForm" lang="ts">
import * as PtSubsidyApi from '@/api/cardCenter/subsidy/ptSubsidy';
import * as PtSubsidyItemApi from '@/api/cardCenter/subsidy/ptSubsidyitem';
import { PtSubsidyForm } from '@/api/cardCenter/subsidy/ptSubsidy/types';
import { PtSubsidyitemVO} from '@/api/cardCenter/subsidy/ptSubsidyitem/types';
import { useI18n } from 'vue-i18n';

defineOptions({ name: 'PtSubsidyForm' });

// 接收父组件传入属性
// const props = defineProps({})

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 国际化
const { t } = useI18n();

/** 数据字典 */
const { CARDBAGTYPE, sys_yes_no, SUBTYPE } = toRefs<any>(proxy?.useDict('CARDBAGTYPE', 'sys_yes_no', 'SUBTYPE'));
// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<PtSubsidyForm>({
  mainId: undefined,
  subsidyName: '',
  subsidyType: '',
  fillMoney: undefined,
  fillDate: undefined,
  bagCode: undefined,
  fillStatus: '',
  auditStatus: '',
  auditUser: undefined,
  auditDate: undefined,
  remark: '',
  ptSubsidyItemList: [],
});
// 表单校验规则
const formRules = reactive({
  mainId: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
  subsidyName: [{ required: true, message: '补助名称不能为空', trigger: 'blur' }],
  subsidyType: [{ required: true, message: '补助类型不能为空', trigger: 'change' }],
  fillMoney: [{ required: true, message: '补助金额不能为空', trigger: 'blur' }],
  fillDate: [{ required: true, message: '预计到账时间不能为空', trigger: 'blur' }],
  bagCode: [{ required: true, message: '入账钱包不能为空', trigger: 'change' }],
});

/** 当前组件方法 */
/** 窗体打开事件 */
const visible = ref(true);
const open = async (type: string, id?: number, isEdit?: boolean) => {
  dialog.visible = true;
  dialog.title = t('action.' + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    visible.value = isEdit;
    itemQuery.mainId = id;
    formLoading.value = true;
    try {
      const res = await PtSubsidyApi.getPtSubsidy(id);
      Object.assign(formData.value, res.data);
      getList();
    } finally {
      formLoading.value = false;
    }
  }
};
/** 表单重置 */
const resetForm = () => {
  
  formData.value = {
    mainId: undefined,
    subsidyName: PtSubsidyApi.getSubsidyName(),
    subsidyType: '1',
    fillMoney: 500,
    fillDate: PtSubsidyApi.getCurrentDateString(),
    bagCode: 3,
    fillStatus: 'N',
    auditStatus: 'N',
    auditUser: undefined,
    auditDate: undefined,
    remark: '',
    ptSubsidyItemList: [],
  };
  formRef.value?.resetFields();
};
// 传回给父组件的属性与方法
// 提供 open 方法，用于打开弹窗
defineExpose({ open });
/** 触发父组件的事件 */
/** 定义 success 事件，用于操作成功后的回调 */
const emit = defineEmits(['success']);
/** 提交按钮 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PtSubsidyForm;
    if (formType.value === 'create') {
      await PtSubsidyApi.addPtSubsidy(data);
      proxy?.$modal.msgSuccess('新增成功');
    } else {
      await PtSubsidyApi.updatePtSubsidy(data);
      proxy?.$modal.msgSuccess('修改成功');
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

/**补助明细列表 */
// 是否加载遮罩层
const loading = ref(false);
// 列表选中的记录Id
const ids = ref<Array<number | string>>([]);
// 单选
const single = ref(true);
// 多选
const multiple = ref(true);
// 总记录数
const total = ref(0);
//查询补助明细列表
const itemQuery = reactive({
    pageNum: 1,
    pageSize: 10,
    mainId: undefined,
    realName: undefined,
    deptName: undefined,
    params: {}
  });
const getList = async () => {
  loading.value = true;
  if(itemQuery.mainId){
    const res = await PtSubsidyItemApi.listPtSubsidyitem(itemQuery);
    formData.value.ptSubsidyItemList = res.rows;
    total.value = res.total;
  }
  loading.value = false;
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: PtSubsidyitemVO[]) => {
  ids.value = selection.map((item) => item.itemId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

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

// 查询窗体Ref
const queryFormRef = ref<ElFormInstance>();

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

/** 删除按钮操作 */
const handleDelete = async (row?: PtSubsidyitemVO) => {
  const _itemIds = row?.mainId || ids.value;
  await proxy?.$modal.confirm('是否确认删除补助设置编号为"' + _itemIds + '"的数据项？').finally(() => (loading.value = false));
  await PtSubsidyItemApi.delPtSubsidyitem(_itemIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};
import UserAccountSelect from '@/components/UserAccountSelect/index.vue';

/**新增按钮弹窗 */
const userAccountSelect = ref();
const openWindowDailog = () =>{
  userAccountSelect.value.open('选择发放补助人员', formData.value.ptSubsidyItemList);
}

const selectUser = (data) => {
  formData.value.ptSubsidyItemList = data
  console.log(formData.value.ptSubsidyItemList)
  formData.value.ptSubsidyItemList.forEach(e => {
    e.fillMoney = formData.value.fillMoney
    e.fillDate = formData.value.fillDate
  });
};

/** 初始化 */
onMounted(() => {});
</script>
