<template>
  <div class="school-manage">
    <Block class="header-block tw-flex tw-items-center tw-justify-between">
      <a-form layout="inline">
        <a-form-item label="学校名称">
          <a-input v-model:value="query.name"></a-input>
        </a-form-item>
        <a-form-item>
          <a-button
            class="search-button"
            type="primary"
            @click="querySchoolList"
            >查询</a-button
          >
        </a-form-item>
      </a-form>
      <a-button
        type="primary"
        class="tw-flex tw-items-center operation-button"
        @click="toggleAddSchoolModal"
      >
        <template #icon>
          <PlusCircleOutlined />
        </template>
        新增
      </a-button>
    </Block>
    <Block class="school-table">
      <a-table
        :columns="columns"
        :data-source="schoolTableData.result"
        emptyText="暂无学校信息"
        @change="currentPageChange"
        :pagination="{
          total: schoolTableData.totalCount,
          pageSize: query.pageSize,
        }"
        :row-class-name="
          (_:any, index:number) => (index % 2 === 1 ? 'table-striped' : null)
        "
      >
        <template #bodyCell="{ column, record, index, text }">
          <template v-if="column.dataIndex === 'index'">
            {{ index + 1 }}
          </template>
          <template v-else-if="column.dataIndex === 'enable'">
            <template v-if="record.enable">
              <CheckCircleFilled style="color: #30bf78" />
            </template>
            <template v-else>
              <CloseCircleFilled style="color: #f4664a" />
            </template>
          </template>
          <template v-else-if="column.dataIndex === 'updateTime'">
            {{ text || record["createTime"] }}
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="tw-flex tw-items-center">
              <span
                class="tw-cursor-pointer tw-p-2"
                @click="updateSchoolStatus(record)"
                >{{ record.enable ? "禁用" : "启用" }}</span
              >
              <span
                class="tw-cursor-pointer tw-p-2 tw-ml-1"
                @click="onEdit(record)"
                >编辑</span
              >
              <a-popover trigger="click">
                <template #content>
                  <VueQrCode
                    type="image/png"
                    :margin="0"
                    :color="{}"
                    :quality="0.9"
                    :value="record.qrCode"
                  />
                </template>
                <span class="tw-cursor-pointer tw-p-2 tw-ml-1">二维码</span>
              </a-popover>
            </div>
          </template>
        </template>
      </a-table>
    </Block>
    <a-modal
      v-model:visible="showModal"
      :title="`${!schoolInfo.id ? '新增' : '编辑'}学校`"
      okText="确定"
      cancelText="取消"
      :maskClosable="false"
      @ok="onAddNewSchool"
      :afterClose="resetFields"
    >
      <a-form :labelCol="{ span: 6 }">
        <a-form-item label="学校编码" v-bind="validateInfos.code">
          <a-input v-model:value="schoolInfo.code"></a-input>
        </a-form-item>
        <a-form-item label="学校名称" v-bind="validateInfos.name">
          <a-input v-model:value="schoolInfo.name"></a-input>
        </a-form-item>
        <a-form-item label="负责人" v-bind="validateInfos.contacts">
          <a-input v-model:value="schoolInfo.contacts"></a-input>
        </a-form-item>
        <a-form-item label="联系方式" v-bind="validateInfos.telephone">
          <a-input
            v-model:value="schoolInfo.telephone"
            maxlength="11"
          ></a-input>
        </a-form-item>
        <a-form-item label="地区" v-bind="validateInfos.region">
          <a-input v-model:value="schoolInfo.region"></a-input>
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="schoolInfo.enable">
            <a-radio :value="true">启用</a-radio>
            <a-radio :value="false">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts" name="PageSchool">
import { reactive, ref, watch } from "vue";
import {
  PlusCircleOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
} from "@ant-design/icons-vue";
import {
  getSchoolListHttp,
  updateSchoolStatusHttp,
  editSchoolInfoHttp,
} from "@/apis/school";
import Block from "@/components/block/index.vue";
import { message, TableColumnType } from "ant-design-vue";
import { Form } from "ant-design-vue";
import VueQrCode from "vue-qrcode";

const showModal = ref(false);

const schoolInfo = reactive<BaseSchoolInfo>({
  code: "",
  contacts: "",
  name: "",
  region: "",
  telephone: "",
  enable: true,
  id: void 0,
});

const schoolRules = {
  code: [{ required: true, message: "请填写学校编码" }],
  name: [{ required: true, message: "请填写学校名称" }],
  contacts: [{ required: true, message: "请填写负责人" }],
  region: [{ required: true, message: "请填写学校地区" }],
  telephone: [
    { required: true, message: "请填写联系方式" },
    { pattern: /\d{11}/, message: "请填写正确联系方式" },
  ],
};

const { validate, validateInfos, resetFields } = Form.useForm(
  schoolInfo,
  schoolRules
);

/** 请求参数 */
const query = reactive<FetchSchoolListQuery>({
  name: "",
  pageNumber: 1,
  pageSize: 10,
});

/** table配置 */
const columns: TableColumnType[] = [
  { title: "序号", dataIndex: "index", align: "center" },
  { title: "学校ID", dataIndex: "id" },
  { title: "学校名称", dataIndex: "name", ellipsis: true },
  { title: "地区", dataIndex: "region",maxWidth: 300 },
  { title: "状态", dataIndex: "enable", align: "center" },
  { title: "负责人", dataIndex: "contacts", ellipsis: true },
  { title: "联系方式", dataIndex: "telephone" },
  { title: "更新时间", dataIndex: "updateTime", ellipsis: true },
  { title: "操作", dataIndex: "operation" },
];

/** 学校列表信息 */
const schoolTableData = reactive<MultiplePageData<SchoolListInfo>>({
  totalCount: 0,
  result: [],
});

/** 显示新增学校弹窗 */
const toggleAddSchoolModal = (show: boolean = true) => {
  showModal.value = show;
};

const currentPageChange = ({ current }: { current: number }) => {
  query.pageNumber = current;
};

/** 查询学校列表 */
const querySchoolList = async () => {
  try {
    const { result = [], totalCount } = await getSchoolListHttp(query);
    Object.assign(schoolTableData, { result, totalCount });
  } catch (error) {
    console.error(error);
  }
};

watch(() => query.pageNumber, querySchoolList);

/* 启用/禁用 */
const updateSchoolStatus = (record: SchoolListInfo) => {
  updateSchoolStatusHttp({ enable: !record.enable, ids: [record.id] }).then(
    querySchoolList
  );
};

/** 编辑学校 */
const onEdit = (record: SchoolListInfo) => {
  Object.assign(schoolInfo, {
    code: record.code,
    contacts: record.contacts,
    name: record.name,
    region: record.region,
    telephone: record.telephone,
    enable: !!record.enable,
    id: record.id,
  });
  toggleAddSchoolModal(true);
};

/** 新增学校 */
const onAddNewSchool = () => {
  validate().then((valid) => {
    if (valid) {
      editSchoolInfoHttp(schoolInfo).then(() => {
        message.success(`${schoolInfo.code ? "修改" : "添加"}成功`);
        toggleAddSchoolModal(false);
        querySchoolList();
      });
    }
  });
};

/** effect */
querySchoolList();
</script>

<style scoped lang="less">
.school-manage {
  .header-block {
    .search-button {
      background-color: @font-color;
      color: @white;
      border: none;
      width: 56px;
      padding: 0;
      &:after {
        display: none;
        opacity: 0;
      }
    }

    .operation-button {
      width: 72px;
      padding: 0;
    }
  }
  .school-table {
  }
}
</style>
