<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      :config="searchConfig"
      v-model="queryParams"
      @search="handleQuery"
      @reset="resetQuery"
      :loading="loading"
    />

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['dz:open:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['dz:open:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <Table
      :data="openList"
      :columns="tableConfigData.columns"
      :actions="tableConfigData.actions"
      :loading="loading"
      :total="total"
      :query-params="queryParams"
      v-model:selected-rows="selectedRows"
      @selection-change="handleSelectionChange"
      @action="handleAction"
      @get-list="getList"
      v-bind="tableConfigData.tableProps"
    >
      <!-- 卡号段插槽 -->
      <template #cardRange="{ row }">
        <span>{{ row.startNo }}~{{ row.endNo }}</span>
      </template>

      <!-- 申请数量插槽 -->
      <template #quantity="{ row }">
        <span>{{ calculateQuantity(row.startNo, row.endNo) }}</span>
      </template>

      <!-- 申请状态插槽 -->
      <template #status="{ row }">
        <el-tag :type="getStatusType(row.status)">
          {{ getStatusText(row.status) }}
        </el-tag>
      </template>

      <!-- 原因插槽 -->
      <template #auditDesc="{ row }">
        <span>{{ row.auditDesc || "-" }}</span>
      </template>
    </Table>

    <!-- 添加或修改开卡申请对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="openRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="起始卡号" prop="startNo">
          <el-input v-model="form.startNo" placeholder="请输入起始卡号" />
        </el-form-item>
        <el-form-item label="截止卡号" prop="endNo">
          <el-input v-model="form.endNo" placeholder="请输入截至卡号" />
        </el-form-item>
        <!-- 省份 -->
        <el-form-item label="省份" prop="province">
          <el-select
              v-model="form.province"
              placeholder="请选择省份"
              style="width: 100%"
              clearable
          >
            <el-option
                v-for="province in provinceList"
                :key="province.dictValue"
                :label="province.dictLabel"
                :value="province.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 学校 -->
        <el-form-item label="学校" prop="schoolId">
          <el-select
              v-model="form.schoolId"
              placeholder="请选择学校"
              :disabled="!form.province"
              style="width: 100%"
          >
            <el-option
                v-for="school in schoolList"
                :key="school.id"
                :label="school.name"
                :value="school.id"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="原因" prop="reason">-->
<!--          <el-input v-model="form.reason" 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>

    <!-- 审核对话框 -->
    <el-dialog
      title="审核开卡申请"
      v-model="reviewOpen"
      width="400px"
      append-to-body
    >
      <div class="detail">
        <div class="item">
          <span class="label"> 卡号段： </span>
          <span class="value">
            {{ reviewForm.startNo }}~{{ reviewForm.endNo }}
          </span>
        </div>
        <div class="item">
          <span class="label"> 申请人： </span>
          <span class="value">
            {{ reviewForm.applicant }}
          </span>
        </div>
        <div class="item">
          <span class="label"> 申请时间： </span>
          <span class="value">
            {{ reviewForm.createTime }}
          </span>
        </div>
        <div class="item">
          <span class="label"> 学校： </span>
          <span class="value">
            {{ reviewForm.schoolName }}
          </span>
        </div>
      </div>
      <el-form
        ref="reviewRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio :value="2">审核通过</el-radio>
            <el-radio :value="3">已拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因" prop="auditDesc">
          <el-input
            v-model="reviewForm.auditDesc"
            placeholder="请输入审核原因"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReview">确 定</el-button>
          <el-button @click="cancelReview">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Open">
import { listOpen, getOpen, addOpen, updateOpen } from "@/api/dz/open";
import SearchForm from "@/components/SearchForm/index.vue";
import Table from "@/components/Table/index.vue";
import formConfig from "./config/form.js";
import tableConfig from "./config/table.js";
import {ref} from "vue";
import {getPaperProvinces} from "@/api/dz/papers.js";
import {getCampusSchoolList} from "@/api/dz/cards.js";
import { deptTreeSelect } from "@/api/system/user";
import { listAgent } from "@/api/dz/agent";

const { proxy } = getCurrentInstance();

const openList = ref([]);
const open = ref(false);
const reviewOpen = ref(false);
const provinceList = ref([]); // 省份列表
const schoolList = ref([]); // 学校列表
const deptOptions = ref([]); // 机构列表
const agentOptions = ref([]); // 代理商列表
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const selectedRows = ref([]);
const { card_status, card_distribute_status, card_time_status, bool_values, card_pay_status, audit_status, card_type } = proxy.useDict( "card_status", "card_distribute_status", "card_time_status", "bool_values", "card_pay_status", "audit_status", "card_type" );

// 搜索配置
const searchConfig = computed(() => {
  const config = formConfig.info.filter((item) => item.search);
  // 动态设置字典选项
  config.forEach((item) => {
    if (item.name === 'status') {
      item.option = audit_status.value || [];
    } else if (item.name === 'cardType') {
      item.option = card_type.value || [];
    } else if (item.name === 'isReopen') {
      item.option = bool_values.value || [];
    } else if (item.name === 'deptId') {
      item.option = deptOptions.value || [];
    } else if (item.name === 'agentId') {
      item.option = agentOptions.value || [];
    }
  });
  return config;
});

// 表格配置
const tableConfigData = computed(() => {
  const config = JSON.parse(JSON.stringify(tableConfig));
  // 动态设置字典选项
  config.columns.forEach((column) => {
    if (column.prop === 'cardType') {
      column.options = card_type.value || [];
    } else if (column.prop === 'isReopen') {
      column.options = bool_values.value || [];
    }
  });
  return config;
});

const data = reactive({
  form: {},
  reviewForm: {
    id: null,
    status: null,
    auditDesc: null,
    startNo: null,
    endNo: null,
    applicant: null,
    createTime: null,
    province:null,
    schoolId: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applicant: null,
    cardNo: null,
    status: null,
    cardType: null,
    isReopen: null,
    deptId: null,
    agentId: null,
  },
  rules: {
    applicant: [{ required: true, message: "申请人不能为空", trigger: "blur" }],
    startNo: [{ required: true, message: "起始卡号不能为空", trigger: "blur" }],
    endNo: [{ required: true, message: "截至卡号不能为空", trigger: "blur" }],
    province: [{ required: true, message: "省份不能为空", trigger: "change" }],
    schoolId: [{ required: true, message: "学校不能为空", trigger: "change" }],
    status: [
      { required: true, message: "申请状态不能为空", trigger: "change" },
    ],
  },
  reviewRules: {
    status: [
      { required: true, message: "审核结果不能为空", trigger: "change" },
    ],
    auditDesc: [],
  },
});

const { queryParams, form, rules, reviewForm, reviewRules } = toRefs(data);

/** 查询开卡申请列表 */
function getList() {
  loading.value = true;
  listOpen(queryParams.value).then((response) => {
    openList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


// 获取省份列表
async function getProvinceList() {
  try {
    const response = await getPaperProvinces();
    if (response.code === 200) {
      provinceList.value = response.data || [];
    }
    schoolList.value = []
  } catch (error) {
    console.error("获取省份列表失败:", error);
  }
}

// 获取校区列表
async function getCampusListData() {
  try {
    const response = await getCampusSchoolList({ campus: false, location: form.value.province, pageNum: 1, pageSize: 1000 });
    if (response.code === 200) {
      schoolList.value = response.data || [];
    }
  } catch (error) {
    console.error("获取校区列表失败:", error);
  }
}

// 获取机构列表
async function getDeptList() {
  try {
    const response = await deptTreeSelect();
    if (response.code === 200) {
      // 将树形结构扁平化
      const flattenDept = (depts) => {
        let result = [];
        depts.forEach(dept => {
          result.push({
            id: dept.id,
            label: dept.label
          });
          if (dept.children && dept.children.length > 0) {
            result = result.concat(flattenDept(dept.children));
          }
        });
        return result;
      };
      deptOptions.value = flattenDept(response.data || []);
    }
  } catch (error) {
    console.error("获取机构列表失败:", error);
  }
}

// 根据deptId获取代理商列表
async function getAgentListByDeptId(deptId) {
  if (!deptId) {
    agentOptions.value = [];
    return;
  }
  try {
    const response = await listAgent({ deptId: deptId });
    if (response.code === 200) {
      // 将代理商列表转换为选项格式（返回的是扁平数组）
      const dataList = response.data || [];
      agentOptions.value = dataList.map(item => ({
        value: item.agentId,
        label: item.name
      }));
    }
  } catch (error) {
    console.error("获取代理商列表失败:", error);
    agentOptions.value = [];
  }
}

// 计算申请数量
function calculateQuantity(startNo, endNo) {
  if (!startNo || !endNo) return 0;
  const start = parseInt(startNo);
  const end = parseInt(endNo);
  return end - start + 1;
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: "待审核",
    2: "审核通过",
    3: "已拒绝",
  };
  return statusMap[status] || "未知";
}

// 获取状态类型
function getStatusType(status) {
  const typeMap = {
    1: "warning",
    2: "success",
    3: "danger",
  };
  return typeMap[status] || "info";
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 取消审核
function cancelReview() {
  reviewOpen.value = false;
  resetReview();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    applicant: null,
    startNo: null,
    endNo: null,
    schoolName: null,
    status: null,
    reason: null,
    createTime: null,
  };
  proxy.resetForm("openRef");
}

// 审核表单重置
function resetReview() {
  reviewForm.value = {
    id: null,
    status: null,
    auditDesc: null,
    startNo: null,
    endNo: null,
    applicant: null,
    createTime: null,
    schoolName: null,
  };
  proxy.resetForm("reviewRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  // 清空代理商列表
  agentOptions.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加开卡申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getOpen(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改开卡申请";
  });
}

/** 审核按钮操作 */
function handleReview(row) {
  resetReview();

  // 从列表中获取对应的数据并填充到reviewForm中
  reviewForm.value = {
    id: row.id,
    status: null,
    auditDesc: null,
    startNo: row.startNo || "-",
    endNo: row.endNo || "-",
    applicant: row.applicant || "-",
    createTime: row.createTime || "-",
    schoolName: row.schoolName || "-",
  };

  reviewOpen.value = true;
}

/** 表格操作处理 */
function handleAction(action, row) {
  switch (action.key) {
    case "review":
      handleReview(row);
      break;
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["openRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateOpen(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOpen(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交审核 */
function submitReview() {
  proxy.$refs["reviewRef"].validate((valid) => {
    if (valid) {
      // 这里应该调用审核API，暂时使用更新API
      const updateData = {
        id: reviewForm.value.id,
        status: reviewForm.value.status,
        auditDesc: reviewForm.value.auditDesc,
      };
      updateOpen(updateData).then((response) => {
        proxy.$modal.msgSuccess("审核成功");
        reviewOpen.value = false;
        getList();
      });
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "dz/open/export",
    {
      ...queryParams.value,
    },
    `open_${new Date().getTime()}.xlsx`
  );
}
// 初始化
onMounted(() => {
  getProvinceList();
  getDeptList();
  getList();
});

// 监听省份变化，获取对应学校
watch(
    () => form.value.province,
    (newProvince) => {
      // 重置学校选择
      form.value.schoolId = null;
      // 获取对应省份的学校列表
      getCampusListData(newProvince);
    }
);

// 监听平台机构变化，获取对应代理商
watch(
    () => queryParams.value.deptId,
    (newDeptId) => {
      // 重置代理商选择
      queryParams.value.agentId = null;
      // 获取对应机构的代理商列表
      getAgentListByDeptId(newDeptId);
    }
);
</script>
<style>
.detail {
  padding-left: 10px;
  .item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
}
</style>
