<template>
  <section class="content">
    <div
      class="box-body"
      v-loading.fullscreen="loading"
      element-loading-text="请稍后..."
    >
      <!-- 表单 -->
      <el-form :inline="true" :model="formSearch">
        <el-form-item label="学校名称">
          <el-input placeholder="请输入学校名称" v-model="formSearch.name" />
        </el-form-item>
        <el-form-item label="学校代码">
          <el-input placeholder="请输入学校代码" v-model="formSearch.code" />
        </el-form-item>
        <el-form-item label="学校域名">
          <el-input
            placeholder="请输入学校域名"
            v-model="formSearch.domainName"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="handleSearchBtn"
            >查询</el-button
          >
          <el-button
            size="small"
            icon="el-icon-refresh"
            @click="resetSearchForm"
            >重置</el-button
          >
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            @click="insert"
            >新增</el-button
          >
        </el-form-item>
      </el-form>

      <div class="block-seperator"></div>

      <span>操作：</span>
      <el-button
        size="small"
        type="success"
        :disabled="noBatchSelected"
        @click="enableOrg"
        icon="el-icon-check"
        >启用</el-button
      >
      <el-button
        size="small"
        type="danger"
        :disabled="noBatchSelected"
        @click="disableOrg"
        icon="el-icon-close"
        >禁用</el-button
      >

      <div style="width: 100%;margin-bottom: 10px;"></div>

      <!-- 添加或修改学校弹出框 -->
      <el-dialog
        title="学校信息"
        width="500px"
        :visible.sync="schoolDialog"
        @close="dialogBeforeClose"
      >
        <el-form
          :inline="true"
          inline-message
          :model="schoolForm"
          ref="schoolForm"
          :rules="rules"
          label-position="right"
          label-width="90px"
          class="editSchoolForm"
        >
          <el-row>
            <el-form-item label="学校代码" label-width="120px" prop="code">
              <el-input
                class="pull_length"
                v-model="schoolForm.code"
                auto-complete="off"
                placeholder="学校域名"
                :disabled="null != schoolForm.id"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="学校名称" label-width="120px" prop="name">
              <el-input
                class="pull_length"
                v-model="schoolForm.name"
                auto-complete="off"
                placeholder="学校名称"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              label="学校域名"
              label-width="120px"
              prop="domainName"
            >
              <el-input
                class="pull_length"
                v-model="schoolForm.domainName"
                auto-complete="off"
                placeholder="学校域名"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="负责人" label-width="120px" prop="contacts">
              <el-input
                class="pull_length"
                v-model="schoolForm.contacts"
                auto-complete="off"
                placeholder="负责人"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="联系方式" label-width="120px" prop="telephone">
              <el-input
                class="pull_length"
                v-model="schoolForm.telephone"
                auto-complete="off"
                placeholder="联系方式"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="考生端产品名" label-width="120px">
              <el-input
                class="pull_length"
                v-model="schoolForm.properties.OE_STUDENT_SYS_NAME"
                auto-complete="off"
                placeholder="考生端产品名"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="状态" label-width="120px" prop="enable">
              <el-radio-group class="pull_right_sm" v-model="schoolForm.enable">
                <el-radio label="true">启用</el-radio>
                <el-radio label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
          <el-row class="d-flex justify-content-center">
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <el-button @click="schoolDialog = false">取 消</el-button>
          </el-row>
        </el-form>
      </el-dialog>

      <!-- 学校产品分配弹出框 -->
      <el-dialog title="产品分配" :visible.sync="functionDialog">
        <div>
          <el-button type="primary" @click="saveOrgFunction">保 存</el-button>
          <el-button @click="functionDialog = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- logo上传弹窗 -->
      <el-dialog title="logo上传" width="350px" :visible.sync="logoDialog">
        <el-form inline>
          <el-row>
            <el-form-item label="学校名称">
              <el-input class="pull_length" v-model="curSchool.name" disabled />
            </el-form-item>
            <el-form-item label="学校代码">
              <el-input class="pull_length" v-model="curSchool.code" disabled />
            </el-form-item>
            <el-form-item>
              <el-upload
                class="form_left"
                ref="upload"
                accept="image/*"
                :action="uploadAction"
                :headers="uploadHeaders"
                :data="uploadData"
                :before-upload="beforeUpload"
                :on-progress="uploadProgress"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :file-list="fileList"
                :auto-upload="false"
                :multiple="false"
              >
                <el-button size="small" slot="trigger" type="primary"
                  >选择文件</el-button
                >&nbsp;
                <el-button size="small" type="success" @click="submitUpload"
                  >确认上传</el-button
                >
                <el-button size="small" type="danger" @click="removeFile"
                  >清空文件</el-button
                >
                <div slot="tip" class="el-upload__tip">只能上传图片</div>
              </el-upload>
            </el-form-item>
          </el-row>
        </el-form>
      </el-dialog>

      <!-- 页面列表 -->
      <el-table
        :data="tableData"
        border
        resizable
        stripe
        @selection-change="selectChange"
      >
        <el-table-column type="selection" width="35" />
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="学校名称">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="left">
              <div style="font-size: 18px;font-family: 新宋体">
                <tr>
                  <td style="color: green">学校名称</td>
                  <td style="color:purple;padding-left: 20px;">
                    {{ scope.row.name }}
                  </td>
                </tr>
                <tr>
                  <td style="color: green">学校代码</td>
                  <td style="color:purple;padding-left: 20px;">
                    {{ scope.row.code }}
                  </td>
                </tr>
                <tr>
                  <td style="color: green">负责人</td>
                  <td style="color:purple;padding-left: 20px;">
                    {{ scope.row.contacts }}
                  </td>
                </tr>
                <tr>
                  <td style="color: green">联系方式</td>
                  <td style="color:purple;padding-left: 20px;">
                    {{ scope.row.telephone }}
                  </td>
                </tr>
              </div>

              <div slot="reference" class="name-wrapper">
                <span>{{ scope.row.name }}</span>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="code" width="190" label="学校代码" />
        <el-table-column prop="domainName" width="190" label="学校域名" />
        <el-table-column
          sortable
          prop="updateTime"
          width="170"
          label="更新时间"
        />
        <el-table-column width="50" label="状态">
          <span slot-scope="scope">
            <span v-if="scope.row.enable">
              <el-tooltip
                class="item"
                effect="dark"
                content="启用"
                placement="left"
              >
                <i class="el-icon-success" style="color:green;"></i>
              </el-tooltip>
            </span>
            <span v-else>
              <el-tooltip
                class="item"
                effect="dark"
                content="禁用"
                placement="left"
              >
                <i class="el-icon-error" style="color:red;"></i>
              </el-tooltip>
            </span>
          </span>
        </el-table-column>
        <el-table-column :context="_self" width="210" prop label="操作">
          <div slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              @click="edit(scope.row)"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button
              v-show="false"
              size="mini"
              type="primary"
              plain
              @click="setLogo(scope.row)"
              icon="el-icon-upload"
              >logo上传</el-button
            >
          </div>
        </el-table-column>
      </el-table>
      <div class="page pull-right">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>
  </section>
</template>

<script>
import { CORE_API } from "@/constants/constants.js";
import { mapState } from "vuex";

export default {
  name: "School",
  data() {
    return {
      formSearch: {
        code: "",
        name: "",
        domainName: ""
      },
      schoolForm: {
        id: null,
        name: "",
        code: "",
        domainName: "",
        contacts: "",
        telephone: "",
        enable: "true",
        remark: "",
        properties: {
          OE_STUDENT_SYS_NAME: null
        }
      },
      functionDialog: false,
      functionDialogInited: false,
      schoolDialog: false,
      logoDialog: false,
      curSchool: {
        name: null,
        code: null
      },
      uploadAction: "",
      uploadHeaders: {},
      uploadData: {},
      fileList: [],
      selectedOrgIds: [],
      loading: true,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      imp: "",
      rules: {
        code: [{ required: true, message: "请输入学校代码", trigger: "blur" }],
        domainName: [
          { required: true, message: "请输入学校域名", trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入学校名称", trigger: "blur" }],
        contacts: [
          { required: true, message: "请输入负责人", trigger: "blur" }
        ],
        telephone: [
          { required: true, message: "请输入联系方式", trigger: "blur" }
        ],
        enable: [{ required: true, message: "请选择状态", trigger: "change" }]
      }
    };
  },
  computed: {
    ...mapState({ user: state => state.user }),
    noBatchSelected() {
      return this.selectedOrgIds.length === 0;
    },
    orgIds() {
      var orgIds = "";
      for (let orgId of this.selectedOrgIds) {
        if (!orgIds) {
          orgIds += orgId;
        } else {
          orgIds += "," + orgId;
        }
      }
      return orgIds;
    }
  },
  methods: {
    resetSearchForm() {
      this.formSearch.code = "";
      this.formSearch.name = "";
      this.formSearch.domainName = "";
    },
    dialogBeforeClose() {
      this.$refs.schoolForm.clearValidate();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchForm();
    },
    getTag(status) {
      if (status == true) {
        return "success";
      } else if (status == false) {
        return "danger";
      }
      return status;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchForm();
    },
    handleSearchBtn() {
      this.currentPage = 1;
      this.searchForm();
    },
    //查询
    searchForm() {
      let searchLock = true;
      setTimeout(() => {
        if (searchLock) {
          this.loading = true;
        }
      }, 500);
      var param = new URLSearchParams(this.formSearch);
      var url =
        CORE_API +
        "/org/rootOrgPage/" +
        (this.currentPage - 1) +
        "/" +
        this.pageSize +
        "?" +
        param;
      this.$httpWithMsg
        .get(url)
        .then(response => {
          this.tableData = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        })
        .finally(() => {
          searchLock = false;
          this.loading = false;
        });
    },
    //启用
    enableOrg() {
      if (this.selectedOrgIds.length === 0) {
        this.$notify({
          type: "warning",
          message: "请选择要启用的机构"
        });
      } else {
        this.$confirm("是否启用这些机构？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          var url = CORE_API + "/org/enable/" + this.orgIds;
          this.$httpWithMsg.put(url).then(() => {
            this.$notify({
              type: "success",
              message: "启用成功！"
            });
            this.searchForm();
          });
        });
      }
    },
    disableOrg() {
      if (this.selectedOrgIds.length === 0) {
        this.$notify({
          type: "warning",
          message: "请选择要禁用的机构"
        });
      } else {
        this.$confirm("是否禁用这些机构？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          var url = CORE_API + "/org/disable/" + this.orgIds;
          this.$$httpWithMsg.put(url, {}).then(() => {
            this.$notify({
              type: "success",
              message: "禁用成功！"
            });
            this.searchForm();
          });
        });
      }
    },
    selectChange(row) {
      this.selectedOrgIds = [];
      row.forEach(element => {
        this.selectedOrgIds.push(element.id);
      });
      console.log(this.selectedOrgIds);
    },
    //重置
    resetForm() {
      this.$refs.schoolForm.resetFields();
    },
    //提交
    submitForm() {
      this.$refs.schoolForm.validate(valid => {
        if (valid) {
          if (null != this.schoolForm.id) {
            //修改
            url = CORE_API + "/org/updateRootOrg";
            this.$httpWithMsg.put(url, this.schoolForm).then(() => {
              this.$notify({
                type: "success",
                message: "修改成功！"
              });
              this.searchForm();
              this.schoolDialog = false;
            });
          } else {
            //新增
            var url = CORE_API + "/org/addRootOrg";
            this.$httpWithMsg.post(url, this.schoolForm).then(() => {
              this.$notify({
                type: "success",
                message: "新增成功！"
              });
              this.searchForm();
              this.schoolDialog = false;
            });
          }
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    //新增
    insert() {
      this.schoolForm.id = null;
      this.schoolForm.name = "";
      this.schoolForm.code = "";
      this.schoolForm.domainName = "";
      this.schoolForm.telephone = "";
      this.schoolForm.contacts = "";
      this.schoolForm.properties.OE_STUDENT_SYS_NAME = "";
      this.schoolForm.enable = "true";

      this.schoolDialog = true;
    },
    //修改
    edit(row) {
      this.schoolForm.id = row.id;
      this.schoolForm.name = row.name;
      this.schoolForm.code = row.code;
      this.schoolForm.domainName = row.domainName;
      this.schoolForm.telephone = row.telephone;
      this.schoolForm.contacts = row.contacts;
      this.schoolForm.properties.OE_STUDENT_SYS_NAME = "";
      this.schoolForm.enable = row.enable ? "true" : "false";

      var url = CORE_API + "/org/allProperties/" + row.id;
      this.$httpWithMsg.get(url).then(response => {
        this.schoolForm.properties = Object.assign(
          this.schoolForm.properties,
          response.data
        );
        this.schoolDialog = true;
      });
    },
    //设置产品
    saveOrgFunction() {},
    //设置logo
    setLogo(row) {
      this.uploadAction = CORE_API + "/org/importLogo/" + row.id;
      this.removeFile();
      this.curSchool.name = row.name;
      this.curSchool.code = row.code;
      this.logoDialog = true;
    },
    initUpload() {
      this.fileList = [];
    },
    beforeUpload(file) {
      console.log(file);
    },
    uploadProgress() {
      console.log("uploadProgress");
    },
    uploadSuccess(response) {
      console.log("uploadSuccess");
      console.log(response);
      if (!response || response.length == 0) {
        this.$notify({
          message: "上传成功",
          type: "success"
        });
      } else {
        this.errMessages = response;
        this.errDialog = true;
      }
      this.fileLoading = false;
      this.logoDialog = false;
      this.removeFile();
      this.searchForm();
    },
    uploadError(response) {
      let json = JSON.parse(response.message);
      if (response.status == 500) {
        this.$notify({
          message: json.desc,
          type: "error"
        });
      }
      this.fileLoading = false;
    },
    //确定上传
    submitUpload() {
      if (!this.checkUpload()) {
        return false;
      }
      this.$refs.upload.submit();
      this.fileLoading = true;
    },
    checkUpload() {
      var fileList = this.$refs.upload.uploadFiles;
      if (fileList.length == 0) {
        this.$notify({
          message: "上传文件不能为空",
          type: "error"
        });
        return false;
      }
      if (fileList.length > 1) {
        this.$notify({
          message: "每次只能上传一个文件",
          type: "error"
        });
        return false;
      }
      for (let file of fileList) {
        var fileName = file.name;
        if (
          !fileName.endsWith(".jpg") &&
          !fileName.endsWith(".gif") &&
          !fileName.endsWith(".png")
        ) {
          this.$notify({
            message: "上传文件必须为[jpg,gif,png]",
            type: "error"
          });
          this.initUpload();
          return false;
        }
      }
      return true;
    },
    //清空文件
    removeFile() {
      this.fileList = [];
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    }
  },
  //初始化查询
  created() {
    this.searchForm();

    this.uploadHeaders = {
      key: this.user.key,
      token: this.user.token
    };
  }
};
</script>

<style scoped>
.page {
  margin-top: 10px;
}

.el-upload {
  width: 80px;
}

.editSchoolForm .pull_length {
  width: 200px;
}
</style>
