<template>
  <div>
    <el-card shadow="never" style="margin-top: 20px">
      <template #header>
        <slot name="header">
          <vxe-toolbar
            custom
            :print="isHasAuth('print')"
            ref="toolbar"
          >
            <template #toolSuffix>
              <vxe-button style="margin-right: 10px;" v-if="isHasAuth('export')" icon="vxe-icon-download" circle @click="exportMethod"></vxe-button>
            </template>
            <template #buttons>
              <el-button
                v-if="isHasAuth('create')"
                icon="el-icon-plus"
                type="primary"
                size="small"
                @click="isShowAdd = true"
                >新增</el-button
              >
              <template v-if="isHasAuth('edit')">
                <el-button
                  size="small"
                  type="primary"
                  plain
                  @click="batchSetIsShow(1)"
                >批量设为显示</el-button>
                <el-button
                  size="small"
                  type="warning"
                  plain
                  @click="batchSetIsShow(0)"
                >批量设为不显示</el-button>
              </template>
              <template v-if="isHasAuth('search')">
                <el-input style="width: 120px;" v-model="select['filter[1][value]']" placeholder="学校名称.." size="small"></el-input>
                <el-select
                  style="width: 120px;"
                  v-model="select['type']"
                  clearable
                  placeholder="请选择学校类型"
                  multiple
                  collapse-tags
                  size="small"
                >
                  <el-option
                    v-for="(option, optionIndex) in schoolType"
                    :key="optionIndex"
                    :label="option['label']"
                    :value="option['value']"
                  ></el-option>
                </el-select>
                <el-select style="width: 100px;" clearable v-model="select['filter[0][value]']" placeholder="区域.." size="small">
                  <el-option v-for="item in area" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-input style="width: 120px;" v-model="select['filter[2][value]']" placeholder="学校星级.." size="small"></el-input>
                <el-select
                  style="width: 110px;"
                  v-model="select['is_show']"
                  clearable
                  placeholder="是否显示"
                  size="small"
                >
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>

                <el-button
                  icon="el-icon-search"
                  type="primary"
                  plain
                  size="small"
                  @click="getList(true)"
                >搜索</el-button
                >
              </template>
              <el-popover
                v-if="isHasAuth('import')"
                placement="bottom-start"
                title="导入"
                width="400"
                trigger="click">
                <template #reference>
                  <el-button type="primary" size="small" icon="el-icon-upload">导入</el-button>
                </template>
                <template #default>
                  <el-upload
                    ref="upload"
                    :action="action"
                    :on-success="uploadSuccess"
                    accept=".xls,.xlsx"
                    :headers="{
                      'Authorization': 'Bearer ' + getToken()
                    }"
                    :auto-upload="false">
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="uploadData">上传到服务器</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="primary" icon="el-icon-download" @click="downloadTemplate">模版下载</el-button>

                    <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
                  </el-upload>
                </template>
              </el-popover>
            </template>
          </vxe-toolbar>
        </slot>
      </template>

      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px"
        :loading="loading"
        :height="tableHeight"
        keep-source
        show-overflow
        :menu-config="{
          className: 'my-menus',
          body: {
            options: [
              [
                {
                  code: 'copy',
                  name: '复制',
                  prefixConfig: { icon: 'vxe-icon-copy' },
                  suffixConfig: { content: 'Ctrl+C' },
                },
                {
                  code: 'remove',
                  name: '删除',
                  prefixConfig: {
                    icon: 'vxe-icon-delete-fill',
                    className: 'color-red',
                  },
                },
              ],
            ],
          },
        }"
        @menu-click="contextMenuClickEvent"
        :row-config="{ isCurrent: true, isHover: true }"
        :column-config="{ resizable: true }"
        :export-config="{}"
        :edit-rules="validRules"
        :edit-config="{
          trigger: 'manual',
          mode: 'row',
          showStatus: true,
          isHover: true,
          autoClear: false,
        }"
        :align="allAlign"
        :data="tableData"
      >
        <vxe-column type="checkbox" width="50" align="center" />
        <vxe-column type="seq" width="58" align="center" />

        <vxe-column
          header-align="center"
          field="name"
          width="480"
          title="学校名称"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        />
        <!-- <vxe-column
          header-align="center"
          field="id"
          width="160"
          title="id"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        />

        <vxe-column
          header-align="center"
          field="from"
          width="160"
          title="学校名称"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        /> -->

        <vxe-column
          align="center"
          field="area_id"
          width="180"
          title="区域"
          :edit-render="{
            name: 'VxeSelect',
            options: area,
            props: { multiple: false },
            optionProps: { value: 'id', label: 'name' },
          }"
        />
        <vxe-column
          v-if="this.select['filter[3][value]']==2"
          align="center"
          field="is_area_3"
          width="180"
          title="是否市三区"
          :edit-render="{
            name: 'VxeSelect',
            options: [{id:0,name:'否'},{id:1,name:'是'}],
            props: { multiple: false },
            optionProps: { value: 'id', label: 'name' },
          }"
        />
        <vxe-column
          header-align="center"
          field="code"
          width="160"
          title="学校代码"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        />

        <vxe-column
          header-align="center"
          field="star"
          width="160"
          title="星级"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        />

        <vxe-column
          header-align="center"
          field="address"
          width="160"
          title="地址"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        />

        <vxe-column
          align="center"
          field="nature"
          width="180"
          title="性质"
          :edit-render="{
            name: 'VxeSelect',
            options: [
              { value: 1, label: '公办' },
              { value: 2, label: '民办' },
            ],
            props: { multiple: false },
            optionProps: { value: 'value', label: 'label' },
          }"
        />

        <vxe-column
          align="center"
          field="is_show"
          width="120"
          title="是否显示"
          :edit-render="{}"
        >
          <template #default="{ row }">
            <span>{{ row.is_show === 0 || row.is_show === '0' ? '否' : '是' }}</span>
          </template>
          <template #edit="{ row }">
            <el-select
              v-model="row.is_show"
              size="mini"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </template>
        </vxe-column>

        <vxe-column
          align="center"
          field="type"
          width="180"
          title="学校类型"
          :edit-render="{
            name: 'VxeSelect',
            options: schoolType,
            props: { multiple: true },
            optionProps: { value: 'value', label: 'label' },
          }"
        />

        <vxe-column
          header-align="center"
          field="build_year"
          width="160"
          title="建校年份"
          :edit-render="{ name: 'input', attrs: { type: 'text' } }"
        />

        <vxe-column
          align="center"
          header-align="center"
          field="introduce"
          width="120"
          title="学校介绍"
          :edit-render="{}"
        >
          <template #default="{ row }">
            <el-button
              slot="reference"
              size="small"
              type="primary"
              icon="el-icon-search"
              @click="
                $refs['RichTextModal'].open({
                  text: row['introduce'],
                  readonly: true,
                  fieldName: 'introduce',
                  row,
                })
              "
              >查看</el-button
            >
          </template>
          <template #edit="{ row }">
            <el-button
              slot="reference"
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="
                $refs['RichTextModal'].open({
                  text: row['introduce'],
                  readonly: false,
                  fieldName: 'introduce',
                  row,
                })
              "
              >编辑</el-button
            >
          </template>
        </vxe-column>

        <vxe-column
          align="center"
          header-align="center"
          field="teacher"
          width="120"
          title="教师信息"
          :edit-render="{}"
        >
          <template #default="{ row }">
            <el-button
              slot="reference"
              size="small"
              type="primary"
              icon="el-icon-search"
              @click="
                $refs['RichTextModal'].open({
                  text: row['teacher'],
                  readonly: true,
                  fieldName: 'teacher',
                  row,
                })
              "
              >查看</el-button
            >
          </template>
          <template #edit="{ row }">
            <el-button
              slot="reference"
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="
                $refs['RichTextModal'].open({
                  text: row['teacher'],
                  readonly: false,
                  fieldName: 'teacher',
                  row,
                })
              "
              >编辑</el-button
            >
          </template>
        </vxe-column>

        <vxe-column
          field="operate"
          header-align="center"
          title="操作"
          min-width="220"
          fixed="right"
        >
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button size="small" type="primary" @click="saveRowEvent(row)"
                >保存</el-button
              >
              <el-button
                size="small"
                type="primary"
                plain
                @click="cancelRowEvent(row)"
                >取消</el-button
              >
            </template>
            <template v-else>
              <el-button
                v-if="isHasAuth('detail')"
                size="small"
                type="primary"
                plain
                @click="detail(row)"
                >查看</el-button
              >
              <el-button
                v-if="isHasAuth('edit')"
                size="small"
                type="warning"
                @click="editRowEvent(row)"
                >编辑</el-button
              >
              <el-button
                v-if="isHasAuth('delete')"
                size="small"
                type="danger"
                @click="destroyRowEvent(row)"
                >删除</el-button
              >
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px; display: flex; justify-content: flex-end"
        :current-page.sync="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size.sync="select.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="
          (e) => {
            select.page_size = e;
            select.page = 1;
            getList();
          }
        "
        @current-change="
          (e) => {
            select.page = e;
            getList();
          }
        "
      />
    </el-card>

    <AddSchool
      ref="AddSchool"
      :area="area"
      :school-type="schoolType"
      :is-show.sync="isShowAdd"
      @refresh="getList"
    />
    <ShowSchool ref="ShowSchool" :area="area" :is-show.sync="isShowDetail" />

    <rich-text-modal
      ref="RichTextModal"
      @confirm="({ row, fieldName, text }) => (row[fieldName] = text)"
    ></rich-text-modal>
  </div>
</template>

<script>
import VxeUI from "vxe-pc-ui";

import RichTextModal from "@/components/RichTextModal/index.vue";

import { authMixin } from "@/mixin/authMixin";
import { uploadSize } from "@/settings";
import {deepCopy, download as downloadByTA, paramsSerializer} from "@/utils";
import { destroy, index, save } from "@/api/school/school";
import AddSchool from "./components/AddSchool.vue";
import ShowSchool from "./components/ShowSchool.vue";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { download } from "@/utils/downloadRequest"
import { index as areaIndex } from "@/api/area/area";
import { getparameter } from "@/api/system/dictionary"

export default {
  name: "School",
  mixins: [authMixin],
  components: {
    RichTextModal,

    AddSchool,
    ShowSchool,
  },
  data() {
    return {
      action: `${process.env.VUE_APP_BASE_API}/api/admin/school/import`,
      uploadSize,
      examineKey: 0,
      isShowAdd: false,
      isShowDetail: false,

      loading: false,
      tableHeight: 400,
      select: {
        page: 1,
        page_size: 20,
        keyword: "",
        show_relation: [],
        'filter[0][key]': 'area_id',
        'filter[0][op]': 'eq',
        'filter[0][value]': '',
        'filter[1][key]': 'name',
        'filter[1][op]': 'like',
        'filter[1][value]': '',
        'filter[2][key]': 'star',
        'filter[2][op]': 'like',
        'filter[2][value]': '',
        'filter[3][key]': 'from',
        'filter[3][op]': 'eq',
        'filter[3][value]': '',
        'type': [],
        is_show: '',
      },
      total: 0,
      allAlign: null,
      tableData: [],
      form: {
        id: "",
        name: "",
        area_id: "",
        is_area_3:'',
        code: "",
        star: "",
        address: "",
        nature: "",
        type: "",
        build_year: "",
        introduce: "",
        teacher: "",
        from: 1,
        is_show: 1,
      },
      validRules: {
        name: [
          {
            required: true,
            message: "学校名称" + "必填",
          },
        ],

        area_id: [
          {
            required: true,
            message: "区域" + "必填",
          },
        ],
      },

      area: [],
      schoolType: [],
    };
  },
  computed: {
    isActiveStatus() {
      return function (row) {
        if (this.$refs["table"]) {
          return this.$refs["table"].isEditByRow(row);
        }
      };
    },
    isHasAuth() {
      return function (auth) {
        return this.auths_auth_mixin.indexOf(auth) !== -1;
      };
    },
  },
  created() {
    this.select['filter[3][value]'] = this.$route.meta?.params?.from
    // this.select['filter[3][value]'] = ''
    this.getArea();
    this.getSchoolType();
    this.getList();
  },
  mounted() {
    this.bindToolbar();
    this.calcTableHeight();
  },
  methods: {
    getToken,
    uploadData() {
      this.$refs.upload.submit();
    },
    uploadSuccess(response) {
      console.log(response)
      if (response.hasOwnProperty('errcode')) {
        this.$message.error(response.errmsg)
      } else {
        this.$message.success(`已导入${response.total}条`)
        this.getList(true)
      }
    },
    exportMethod() {
      this.$confirm("请选择导出方式", "提示", {
        confirmButtonText: "全量导出",
        cancelButtonText: "部分导出",
        distinguishCancelAndClose: true,
      })
        .then((_) => {
          const tableColumns = this.$refs['table'].getFullColumns()

          let export_fields = {}

          Object.keys(this.form).forEach(key => {
            if(key=='area_id'){
              export_fields['area_id_text'] = tableColumns.find(col => col.field === key)?.title || key
            }else if(key=='from'){
              export_fields['from_text'] = '类型'
            }else if(key=='nature'){
              export_fields['nature_text'] = tableColumns.find(col => col.field === key)?.title || key
            }else if(key=='type'){
              export_fields['type_text'] = tableColumns.find(col => col.field === key)?.title || key
            }else if(key=='is_show'){
              export_fields['is_show_text'] = tableColumns.find(col => col.field === key)?.title || key
            }else if(key=='is_area_3'||key=='id'){

            }else{
              export_fields[key] = tableColumns.find(col => col.field === key)?.title || key
            }
          })
          console.log("tableColumns",tableColumns,export_fields)
          // return
          download("/api/admin/school/index", "get", {
            ...this.select,
            page: 1,
            page_size: 9999,
            is_export: 1,
            export_fields
          }, `${this.$route.meta.title}_${this.$moment().valueOf()}.xlsx`,paramsSerializer);
        })
        .catch((action) => {
          if (action === "cancel" && this.$refs["table"]) {
            this.$refs["table"].openExport();
          }
        });
    },
    calcTableHeight() {
      let clientHeight = document.documentElement.clientHeight;
      let cardTitle = document
        .querySelector(".el-card__header")
        ?.getBoundingClientRect()?.height;
      let search = document
        .querySelector(".vxe-toolbar")
        ?.getBoundingClientRect()?.height;
      let paginationHeight =
        (document.querySelector(".el-pagination")?.getBoundingClientRect()
          ?.height ?? 0) + 10; //分页的高度
      let topHeight = 50; //页面 头部
      let padding = 80;
      let margin = 20;
      this.tableHeight =
        clientHeight -
        cardTitle -
        search -
        paginationHeight -
        topHeight -
        padding -
        margin;
    },
    contextMenuClickEvent({ menu, row, column }) {
      switch (menu.code) {
        case "copy":
          // 示例
          if (row && column) {
            if (VxeUI.clipboard.copy(row[column.field])) {
              this.$message.success("已复制到剪贴板！");
            }
          }
          break;
        case "remove":
          if (row && column) {
            this.destroyRowEvent(row);
          }
        default:
      }
    },
    async detail(row) {
      await this.$refs["ShowSchool"].getDetail(row.id);
      this.isShowDetail = true;
    },

    async getArea() {
      try {
        const res = await areaIndex(
          {
            page: 1,
            page_size: 999,
          },
          false
        );
        this.area = res.data;
      } catch (err) {
        console.error(err);
      }
    },
    async getSchoolType() {
      try {
        const { detail } = await getparameter(
          {
            number: 'school_type'
          },
          false
        );
        this.schoolType = detail?.map(i => ({
          value: i.value,
          label: i.value
        }));
      } catch (err) {
        console.error(err);
      }
    },

    uploadMethod(file) {
      const formData = new FormData();
      formData.append("file", file);
      window.$_uploading = true;
      return axios
        .post(process.env.VUE_APP_UPLOAD_API, formData, {
          headers: {
            Authorization: `Bearer ${getToken()}`,
          },
        })
        .then((response) => {
          window.$_uploading = false;
          if (response.status === 200 && !response.data.code) {
            return {
              response: response.data,
              name: response.data.original_name,
              url: response.data.url,
            };
          } else {
            this.$message.error("上传失败");
          }
        })
        .catch((_) => {
          window.$_uploading = false;
        });
    },
    bindToolbar() {
      this.$nextTick(() => {
        if (this.$refs["table"] && this.$refs["toolbar"]) {
          this.$refs["table"].connect(this.$refs["toolbar"]);
        }
      });
    },

    editRowEvent(row) {
      if (this.$refs["table"]) {
        this.$refs["table"].setEditRow(row);
      }
    },
    async batchSetIsShow(isShow) {
      const $table = this.$refs["table"];
      if (!$table) {
        return;
      }
      const records = $table.getCheckboxRecords();
      if (!records.length) {
        this.$message.warning("请先勾选学校");
        return;
      }
      const text = isShow === 1 ? "显示" : "不显示";
      try {
        await this.$confirm(
          `确定将已选 ${records.length} 所学校批量设为「${text}」吗？`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
      } catch {
        return;
      }
      this.loading = true;
      try {
        await Promise.all(
          records.map((row) => save({ id: row.id, is_show: isShow }, false))
        );
        this.$message.success("设置成功");
        $table.clearCheckboxRow();
        await this.getList();
      } catch (err) {
        console.error(err);
        this.$message.error("设置失败，请重试");
        await this.getList();
      } finally {
        this.loading = false;
      }
    },
    cancelRowEvent(row) {
      if (this.$refs["table"]) {
        this.$refs["table"].clearEdit().then(() => {
          // 还原行数据
          this.$refs["table"].revertData(row);
        });
      }
    },

    async getList(isRefresh=false) {
      if(isRefresh) {
        this.select.page = 1
      }
      this.loading = true;
      try {
        const res = await index(this.select, false);
        this.tableData = (res.data || []).map((row) => ({
          ...row,
          is_show:
            row.is_show === 0 || row.is_show === '0' || row.is_show === false
              ? 0
              : 1,
        }));
        this.total = res.total;
        this.loading = false;
      } catch (err) {
        console.error(err);
        this.loading = false;
      }
    },

    async saveRowEvent(row) {
      if (window.$_uploading) {
        this.$message.warning("文件正在上传中");
        return;
      }
      try {
        const errMap = await this.$refs["table"].validate();
        if (errMap) {
          throw new Error(errMap);
        }
        await this.$confirm("确认保存？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        });
        await this.$refs["table"].clearEdit();
        let form = deepCopy(this.form);
        for (const key in form) {
          form[key] = row[key];
        }

        this.loading = true;
        await save(form, false);
        await this.getList();
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },
    async destroyRowEvent(row) {
      try {
        await this.$confirm("确认删除？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        });
        this.loading = true;
        if (row.id) {
          await destroy(
            {
              id: row.id,
            },
            false
          );
          await this.getList();
        } else {
          console.log(row);
          this.tableData.splice(
            this.tableData.findIndex((i) => i._X_ROW_KEY === row._X_ROW_KEY),
            1
          );
        }
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },

    downloadTemplate() {
      getparameter({
        number: 'download_url'
      }).then(({ detail }) => {
        const url = detail?.find(i => i.value === (this.$route.meta?.params?.from == 1 ? 'school' : 'independent_school'))?.remark
        if (url) {
          downloadByTA(url)
        }
      })
    }
  },
};
</script>

<style scoped lang="scss">
::v-deep .vxe-buttons--wrapper > * + * {
  margin-left: 10px;
}
::v-deep .el-card__header {
  padding: 6px 20px;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
