<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <div v-show="showSearch">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="100px">
              <el-form-item label="职称等级" prop="moneyType">
                <el-input v-model="queryParams.moneyType" clearable placeholder="请输入职称等级"
                          @keyup.enter="handleQuery" />
              </el-form-item>
              <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-form>
          </el-card>
        </div>

        <el-card class="mt-[10px]" shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button icon="Plus" type="primary" @click="add">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button icon="Download" plain type="info" @click="handleDownloadTem">下载模板</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button icon="Upload" type="warning" @click="exportList">导入</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="manageList">
            <el-table-column
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
              :align="align || 'center'"
              :label="label"
              :min-width="minWidth || '100px'"
              prop="expertName"
            >
              <template #default="{ row }">
                <span v-if="prop == 'moneyNumber'">{{ row.moneyNumber }}元/次</span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作"
                             min-width="120px">
              <template #default="{ row }">
                <el-button link type="primary" @click="Edit(row)">编辑</el-button>
                <el-button link type="danger" @click="deleteRow(row.moneyId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" v-model:limit="page.pageSize" v-model:page="page.pageNum"
                      :total="page.total" @pagination="getList" />
        </el-card>
        <el-dialog v-model="dialogFormVisible" :before-close="Cancel" :title="dialogTitle" width="600px">
          <el-form ref="FormRef" :model="form" :rules="rules" label-width="auto">
            <el-form-item label="职称等级" prop="moneyType">
              <el-input v-model="form.moneyType" clearable placeholder="请输入职称等级" />
            </el-form-item>
            <el-form-item label="费用标准" prop="moneyNumber">
              <el-input v-model="form.moneyNumber" clearable placeholder="请输入费用标准"
                        @input="(value) => value.replace(/[^\d.]/g,'')">
                <template #append>
                  <span>元/次</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="计费方式" prop="moneyMethod">
              <el-input v-model="form.moneyMethod" clearable placeholder="请输入计费方式" />
            </el-form-item>
            <el-form-item label="结算周期" prop="moneyCycle">
              <el-input v-model="form.moneyCycle" clearable placeholder="请输入结算周期" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :rows="5" clearable maxlength="500" placeholder="请输入备注"
                        resize="none" show-word-limit type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="Cancel">取 消</el-button>
              <el-button type="primary" @click="save">确 定</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 专家费用管理导入对话框 -->
        <el-dialog v-model="upload.open" :title="upload.title" append-to-body width="400px">
          <el-upload
            ref="uploadRef"
            :action="upload.url"
            :auto-upload="false"
            :disabled="upload.isUploading"
            :headers="upload.headers"
            :limit="1"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            accept=".xlsx, .xls"
            drag
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="text-center el-upload__tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
              </div>
            </template>
          </el-upload>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { addManage, deleteManage, getTableList, updateManage } from '@/api/expertMoneyConfig/manage';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const manageList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}

const headers = ref<Header[]>([
  {
    label: '职称等级',
    prop: 'moneyType'
  },
  {
    label: '费用标准',
    prop: 'moneyNumber'
  },
  {
    label: '计费方式',
    prop: 'moneyMethod'
  },
  {
    label: '结算周期',
    prop: 'moneyCycle'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '创建日期',
    prop: 'createTime'
  },
  {
    label: '更新日期',
    prop: 'updateTime'
  }
]);

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  moneyType: ''
});


const getList = async () => {
  loading.value = true;
  let params = {
    ...page.value,
    ...queryParams.value
  };
  delete params.total;
  const res = await getTableList(params);
  manageList.value = res.rows;
  loading.value = false;
  page.value.total = res.total;
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const dialogFormVisible = ref(false);
const dialogTitle = ref('');
const dialogType = ref('add');
const form = reactive({
  id: undefined,
  moneyType: '',
  moneyNumber: '',
  moneyMethod: '',
  moneyCycle: '',
  remark: ''
});
const rules = reactive({
  moneyType: [
    { required: true, message: '请输入职称等级', trigger: 'blur' }
  ],
  moneyNumber: [
    { required: true, message: '请输入费用标准', trigger: 'blur' }
  ],
  moneyMethod: [
    { required: true, message: '请输入计费方式', trigger: 'blur' }
  ],
  moneyCycle: [
    { required: true, message: '请输入结算周期', trigger: 'blur' }
  ]
});
/**
 * 新增
 */
const add = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'add';
  dialogTitle.value = '新增';
};
/**
 * 编辑
 */
const Edit = (row: any) => {
  dialogFormVisible.value = true;
  dialogType.value = 'edit';
  dialogTitle.value = '编辑';
  Object.assign(form, row);
};
/**
 * 保存
 */
const FormRef = ref(null);
const save = () => {
  FormRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    ElMessageBox.confirm(`确定${dialogTitle.value}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const params: any = {
        ...form
      };
      const json = {
        add: addManage,
        edit: updateManage
      };
      if (dialogType.value == 'edit') {
        delete params.createTime;
        delete params.updateTime;
      }
      let res = await json[dialogType.value](params);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: `${dialogTitle.value}成功！`,
        type: 'success'
      });
      Cancel();
      await getList();
    });
  });
};
/**
 * 取消
 */
const Cancel = () => {
  // FormRef.value?.resetFields();
  form.id = undefined;
  form.moneyType = '';
  form.moneyNumber = '';
  form.moneyMethod = '';
  form.moneyCycle = '';
  form.remark = '';
  dialogFormVisible.value = false;
};

/**
 * 删除
 */
const deleteRow = (id: any) => {
  ElMessageBox.confirm('确定删除该条数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await deleteManage(id);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }
    ElNotification({
      title: '提示',
      message: '删除成功！',
      type: 'success'
    });
    await getList();
  });
};
/**
 * 下载模板
 */
const handleDownloadTem = () => {
  proxy?.download('/zjk-api/expertMoneyConfig/export-template', {}, `专家费用管理导入模板.xlsx`);
};
/**
 * 导入
 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/zjk-api/expertMoneyConfig/imports'
});
const exportList = () => {
  upload.title = '专家费用管理导入';
  upload.open = true;
};
const uploadRef = ref<ElUploadInstance>();
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  if (response.code == 200) {
    ElNotification({
      title: '提示',
      message: '导入成功',
      type: 'success'
    });
  } else {
    ElNotification({
      title: '提示',
      message: response.msg,
      type: 'error'
    });
  }
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

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