<template>
  <div class="school">
    <div class="header">
      <div>
        <RadioGroup v-model="form_search.ltype" @on-change="seach">
          <Radio :label="1" :value="1">中文</Radio>
          <Radio :label="2" :value="2">英文</Radio>
        </RadioGroup>
        <Input
          style="width: 200px; margin-left: 20px"
          placeholder="请输入学校名称"
          @on-enter="seach"
          @on-search="seach"
          search
          v-model="form_search.schoolname"
        />
      </div>
      <Button @click="add" type="primary"> 添加 </Button>
    </div>
    <div>
      <Table border :data="school.list" :columns="columns">
        <template slot-scope="{ row }" slot="schoollogo">
          <img
            class="img"
            v-if="row.schoollogo"
            :src="$api.showImageUrl + row.schoollogo"
            v-viewer
          />
        </template>
      </Table>
      <div class="foot_page" v-if="school.total > 0">
        <Page
          :total="school.total"
          @on-change="changePage"
          :current="form_search.page"
          show-total
        ></Page>
      </div>
    </div>
    <!--    添加-->
    <Modal
      v-model="add_form.show"
      class="modal1"
      :mask-closable="false"
      title="添加学校"
    >
      <Form
        :label-width="90"
        label-position="right"
        ref="AddForm"
        :rules="addFormRules"
        :model="add_form"
      >
        <FormItem label="语言" prop="ltype">
          <RadioGroup v-model="add_form.ltype">
            <Radio :label="1">中文</Radio>
            <Radio :label="2">英文</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="服务案例" prop="schoolname">
          <Input v-model="add_form.schoolname" placeholder="请输入学校名称" />
        </FormItem>
        <FormItem label="序号">
          <Input v-model="add_form.slorder" number placeholder="请输入序号" />
        </FormItem>
        <div class="uploadimg">
          <div class="uploadimg_title">图片</div>
          <div class="upload">
            <Upload
              action
              class="file_left_up"
              :format="pictureFormat"
              :accept="getPictureAccept()"
              :before-upload="
                (file) => {
                  handleUpload(file);
                  return false;
                }
              "
            >
              <div
                class="upload-img"
                v-if="!this.add_form.schoollogo"
                style="padding-top: 10px"
              >
                <Icon
                  type="ivu-icon ivu-icon- iconfont icon-shangchuan"
                  size="42"
                  color="#e6e6e6"
                />
                <p
                  class="shangchuan_btn"
                  style="margin-top: 10px; font-size: 14px; text-align: center"
                >
                  上传图片
                </p>
              </div>
              <div v-else>
                <img
                  class="upload-img"
                  :src="$api.showImageUrl + add_form.schoollogo"
                />
              </div>
            </Upload>
          </div>
          <div class="uptype">
            <p>支持上传格式（10MB以内）:</p>
            <p>jpg、jpeg、png、bmp、jfif、webp.</p>
          </div>
        </div>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button @click="add_form.show = false">取消</Button>
        <Button @click="toSaveAdd()" type="primary">保存</Button>
      </div>
    </Modal>
    <!--    修改-->
    <Modal
      v-model="revise_data.show"
      class="modal1"
      :mask-closable="false"
      title="修改学校"
    >
      <Form
        :label-width="90"
        label-position="right"
        ref="reForm"
        :rules="reviseFormRules"
        :model="revise_data.data"
      >
        <FormItem label="学校名称" prop="schoolname">
          <Input
            v-model="revise_data.data.schoolname"
            placeholder="请输入学校名称"
          />
        </FormItem>
        <FormItem label="序号">
          <Input
            v-model="revise_data.data.slorder"
            number
            placeholder="请输入序号"
          />
        </FormItem>
        <div class="uploadimg">
          <div class="uploadimg_title">图片</div>
          <div class="upload">
            <Upload
              action
              class="file_left_up"
              :format="pictureFormat"
              :accept="getPictureAccept()"
              :before-upload="
                (file) => {
                  handleUpload(file);
                  return false;
                }
              "
            >
              <div
                class="upload-img"
                v-if="!this.revise_data.data.schoollogo"
                style="padding-top: 10px"
              >
                <Icon
                  type="ivu-icon ivu-icon- iconfont icon-shangchuan"
                  size="42"
                  color="#e6e6e6"
                />
                <p
                  class="shangchuan_btn"
                  style="margin-top: 10px; font-size: 14px; text-align: center"
                >
                  上传图片
                </p>
              </div>
              <div v-else>
                <img
                  class="upload-img"
                  :src="$api.showImageUrl + revise_data.data.schoollogo"
                />
              </div>
            </Upload>
          </div>
          <div class="uptype">
            <p>支持修改格式（10MB以内）:</p>
            <p>jpg、jpeg、png、bmp、jfif、webp.</p>
          </div>
        </div>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button @click="revise_data.show = false">取消</Button>
        <Button @click="revise()" type="primary">保存</Button>
      </div>
    </Modal>
    <!-- 等待窗 -->
    <Spin fix v-if="showLoading" style="background-color: transparent">
      <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
      <div>加载中</div>
    </Spin>
  </div>
</template>

<script>
import axios from "axios";
import { sl_list, sl_save, sl_update, sl_del } from "@/api/index";
import { dateFormat } from "@/utils/index";
import { pictureFormat } from "@/utils/fileConfig";
export default {
  data() {
    return {
      pictureFormat,
      userInfo: {},
      showLoading: false,
      form_search: {
        page: 1,
        size: 10,
        schoolname: "",
        ltype: 1 //1中文2英文
      },
      school: {
        total: 0,
        list: []
      },
      columns: [
        {
          title: "序号",
          align: "center",
          key: "slorder",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.form_search.page - 1) * this.form_search.size +
                1
            );
          }
        },
        {
          title: "学校名称",
          key: "schoolname",
          align: "center"
        },
        {
          title: "学校图标",
          slot: "schoollogo",
          align: "center",
          width: 180
        },
        {
          title: "排序",
          align: "center",
          key: "slorder",
          width: 70
        },
        {
          title: "创建人",
          key: "createname",
          align: "center",
          width: 140
        },
        {
          title: "创建时间",
          key: "createtime",
          width: 200,
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 150,
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {
                  style: {
                    cursor: "pointer"
                  },
                  class: "theme_color",
                  on: {
                    click: () => {
                      this.$refs["reForm"].resetFields();
                      this.revise_data = {
                        show: true,
                        data: JSON.parse(JSON.stringify(params.row))
                      };
                    }
                  }
                },
                "修改"
              ),
              h(
                "span",
                {
                  style: {
                    margin: "0 10px"
                  },
                  class: "theme_color"
                },
                "|"
              ),
              h(
                "span",
                {
                  style: {
                    cursor: "pointer"
                  },
                  class: "red",
                  on: {
                    click: () => {
                      let content = "您确定要删除吗？";
                      this.$Modal.confirm({
                        title: "提示",
                        content: content,
                        onOk: () => {
                          this.del(params.row);
                        },
                        onCancel: () => {}
                      });
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ], //列表表格
      add_form: {
        show: false,
        schoolname: "",
        schoollogo: "",
        slorder: 0,
        ltype: 1
      },
      revise_data: {
        show: false,
        data: {}
      },
      reviseFormRules: {
        schoolname: [
          {
            required: true,
            message: "学校名称不能为空",
            trigger: "blur"
          }
        ],
        slorder: [
          {
            required: true,
            message: "序号不能为空",
            trigger: "blur"
          }
        ]
      },
      addFormRules: {
        ltype: [
          {
            required: true,
            type: "number",
            message: "请选择语言",
            trigger: "change"
          }
        ],
        schoolname: [
          {
            required: true,
            message: "学校名称不能为空",
            trigger: "blur"
          }
        ],
        slorder: [
          {
            required: true,
            message: "序号不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem("xhWebAdminUser"));
    this.init();
  },
  methods: {
    getPictureAccept() {
      return this.pictureFormat
          .map((v) => {
            return `.${v}`;
          })
          .join(",");
    },
    seach() {
      this.form_search.page = 1;
      this.init();
    },
    init() {
      sl_list(this.form_search).then((res) => {
        if (res.code == 0) {
          this.school.list = res.obj.list.map((v) => {
            v.createtime = dateFormat(v.createtime);
            return v;
          });
          this.school.total = res.obj.total;
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    add() {
      this.$refs["AddForm"].resetFields();
      this.add_form.show = true;
      this.add_form.ltype = JSON.parse(JSON.stringify(this.form_search.ltype));
      this.add_form.slorder = this.school.total + 1;
    },
    revise() {
      this.$refs["reForm"].validate((valid) => {
        if (valid) {
          if (!this.revise_data.data.schoollogo) {
            this.$Message.error("请上传图片");
            return false;
          }
          sl_update({
            schoolname: this.revise_data.data.schoolname,
            schoollogo: this.revise_data.data.schoollogo,
            slorder: this.revise_data.data.slorder,
            slid: this.revise_data.data.slid,
            ltype: this.revise_data.data.ltype
          }).then((res) => {
            if (res.code == 0) {
              this.revise_data.show = false;
              this.$Message.success(res.msg);
              this.init();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    del(data) {
      sl_del({ slid: data.slid }).then((res) => {
        if (res.code == 0) {
          if (this.form_search.page != 1 && this.school.list.length == 1) {
            this.form_search.page--;
          }
          this.init();
          this.$Message.success(res.msg);
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    //确定添加
    toSaveAdd() {
      this.$refs["AddForm"].validate((valid) => {
        if (valid) {
          if (!this.add_form.schoollogo) {
            this.$Message.error("请上传图片");
            return false;
          }
          sl_save({
            schoolname: this.add_form.schoolname,
            schoollogo: this.add_form.schoollogo,
            ltype: this.add_form.ltype,
            slorder: this.add_form.slorder,
            createid: this.userInfo.userid
          }).then((res) => {
            if (res.code == 0) {
              this.add_form.show = false;
              this.add_form.schoolname = "";
              this.add_form.schoollogo = "";
              this.$Message.success(res.msg);
              this.init();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    handleUpload(file) {
      let that = this;
      let size = file.size / 1024 / 1024;
      if (size > 2) {
        this.$Message.error("图片太大，不能超过2M!");
        return false;
      }
      let formData = new FormData();
      formData.append("file", file);
      formData.append("savefolder", "schoollogo");
      let url = that.$api.baseUrl + "file/upload";
      that.showLoading = true;
      axios
        .post(url, formData, {
          timeout: 1000 * window._config.axiosFileTimeout
        })
        .then((res) => {
          that.showLoading = false;
          if (res.data.code === 0) {
            if (this.revise_data.show) {
              //修改
              that.revise_data.data.schoollogo = res.data.obj;
            } else {
              //添加
              that.add_form.schoollogo = res.data.obj;
              that.init();
            }
          } else {
            that.$Message.error("图片上传失败");
          }
        })
        .catch(() => {
          that.showLoading = false;
          that.$Message.error("图片上传失败");
        });
    },
    changePage(page) {
      this.form_search.page = page;
      this.init();
    }
  }
};
</script>

<style scoped lang="less">
.header {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
/deep/ .theme_color {
  color: #2d8cf0;
}
/deep/ .red {
  color: red;
}
.img {
  width: 60px;
  height: 60px;
  cursor: pointer;
  margin-top: 5px;
}
.upload {
  width: 200px;
  height: 100px;
  border: 1px solid #dcdee2;
  box-sizing: border-box;
  cursor: pointer;
  &:hover {
    color: #2d8cf0;
    border: 1px solid #2d8cf0;
    .upload-img,
    .icon-shangchuan,
    .shangchuan_btn {
      color: inherit !important;
    }
  }
  .upload-img {
    width: 198px;
    height: 98px;
    text-align: center;
    object-fit: cover;
  }
}
.uploadimg {
  display: flex;
  .uploadimg_title {
    width: 90px;
    text-align: right;
    padding-right: 10px;
  }
}
.uptype{
  padding-left: 10px;
}
</style>
