<template>
  <section class="content">
    <div class="box box-info">
      <div class="box-body">
        <!-- 表单 -->
        <el-form
          :inline="true"
          :model="formSearch"
          label-position="right"
          label-width="100px"
        >
          <el-row :gutter="5">
            <el-form-item label="学校名称" class="pull-left">
              <el-input
                placeholder="请输入学校名称"
                v-model="formSearch.name"
              />
            </el-form-item>
            <el-form-item label="学校代码" class="pull-left">
              <el-input
                placeholder="请输入学校代码"
                v-model="formSearch.code"
              />
            </el-form-item>
            <el-form-item label="学校域名" class="pull-left">
              <el-input
                placeholder="请输入学校域名"
                v-model="formSearch.domainName"
              />
            </el-form-item>
            <el-form-item class="pull-right">
              <el-button
                size="small"
                type="primary"
                icon="search"
                @click="searchForm"
              >
                查询
              </el-button>
              <el-button
                size="small"
                type="primary"
                icon="plus"
                @click="insert"
              >
                新增
              </el-button>
              <el-button size="small" type="success" @click="enableOrg">
                <i class="fa fa-check" aria-hidden="true"></i>启用
              </el-button>
              <el-button size="small" type="danger" @click="disableOrg">
                <i class="fa fa-close" aria-hidden="true"></i>禁用
              </el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <!-- 添加或修改学校弹出框 -->
        <el-dialog title="学校信息" :visible.sync="schoolDialog">
          <el-form
            :inline="true"
            :model="schoolForm"
            ref="schoolForm"
            :rules="rules"
            label-position="right"
            label-width="90px"
          >
            <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="pull_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上传" :visible.sync="logoDialog">
          <el-form>
            <el-row>
              <el-form-item label="学校名称" label-width="120px">
                <el-input
                  class="pull_length"
                  v-model="curSchool.name"
                  disabled
                />
              </el-form-item>
              <el-form-item label="学校代码" label-width="120px">
                <el-input
                  class="pull_length"
                  v-model="curSchool.code"
                  disabled
                />
              </el-form-item>
              <el-form-item style="margin-left:20px">
                <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="domainName" width="190" label="学校域名" />
          <el-table-column prop="updateTime" width="170" label="更新时间" />
          <el-table-column width="70" label="状态">
            <span slot-scope="scope">
              <!-- <el-tag :type="getTag(scope.row.enable)"> -->
              {{ getStatus(scope.row.enable) }}
              <!-- </el-tag> -->
            </span>
          </el-table-column>
          <el-table-column :context="_self" width="200" 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
                size="mini"
                type="primary"
                plain
                @click="setLogo(scope.row)"
              >
                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"
            layout="total, prev, pager, next, jumper"
            :total="total"
          />
        </div>
      </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 }),
    orgIds() {
      var orgIds = "";
      for (let orgId of this.selectedOrgIds) {
        if (!orgIds) {
          orgIds += orgId;
        } else {
          orgIds += "," + orgId;
        }
      }
      return orgIds;
    }
  },
  methods: {
    getStatus(status) {
      if (status == true) {
        return "启用";
      } else if (status == false) {
        return "禁用";
      }
      return status;
    },
    getTag(status) {
      if (status == true) {
        return "success";
      } else if (status == false) {
        return "danger";
      }
      return status;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchForm();
    },
    //查询
    searchForm() {
      this.loading = true;
      var param = new URLSearchParams(this.formSearch);
      var url =
        CORE_API +
        "/org/rootOrgPage/" +
        (this.currentPage - 1) +
        "/" +
        this.pageSize +
        "?" +
        param;
      this.$http.get(url).then(response => {
        this.tableData = response.data.list;
        this.total = response.data.total;
        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.$http
            .put(url)
            .then(() => {
              this.$notify({
                type: "success",
                message: "启用成功！"
              });
              this.searchForm();
            })
            .catch(response => {
              if (response.status == 500) {
                this.$notify({
                  showClose: true,
                  message: response.data.desc,
                  type: "error"
                });
              }
            });
        });
      }
    },
    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.$http
            .put(url, {})
            .then(() => {
              this.$notify({
                type: "success",
                message: "禁用成功！"
              });
              this.searchForm();
            })
            .catch(response => {
              if (response.status == 500) {
                this.$notify({
                  showClose: true,
                  message: response.data.desc,
                  type: "error"
                });
              }
            });
        });
      }
    },
    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.$http.put(url, this.schoolForm).then(
              () => {
                this.$notify({
                  type: "success",
                  message: "修改成功！"
                });
                this.searchForm();
                this.schoolDialog = false;
              },
              response => {
                if (response.status == 500) {
                  this.$notify({
                    showClose: true,
                    message: response.data.desc,
                    type: "error"
                  });
                }
              }
            );
          } else {
            //新增
            var url = CORE_API + "/org/addRootOrg";
            this.$http.post(url, this.schoolForm).then(
              () => {
                this.$notify({
                  type: "success",
                  message: "新增成功！"
                });
                this.searchForm();
                this.schoolDialog = false;
              },
              response => {
                if (response.status == 500) {
                  this.$notify({
                    showClose: true,
                    message: response.data.desc,
                    type: "error"
                  });
                }
              }
            );
          }
        } 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.$http.get(url).then(
        response => {
          this.schoolForm.properties = Object.assign(
            this.schoolForm.properties,
            response.data
          );
          this.schoolDialog = true;
        },
        response => {
          this.$notify({
            type: "error",
            message: response.data.desc
          });
        }
      );
    },
    //设置产品
    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() {
      this.$notify({
        message: "上传失败",
        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;
}
</style>
