<template>
  <div class="main_root">
    <div class="search_header">
      <div class="search_left">
        <Select
          :transfer="true"
          v-model="searchForm.regionid"
          @on-change="searchList()"
          style="margin-right: 10px; width: 150px"
        >
          <Option :value="0">所有区域</Option>
          <Option
            v-for="item in searchForm.dropList"
            :value="item.regionid"
            :key="item.regionid"
            >{{ item.regionName }}</Option
          >
        </Select>
        <Select
          :transfer="true"
          v-model="searchForm.provinceid"
          style="width: 120px; margin: 0 10px"
          placeholder="请选择省份"
          @on-change="provinceChange(searchForm.provinceid, 1)"
        >
          <Option
            v-for="item in areaList"
            :value="item.areaCode"
            :key="item.areaCode"
            >{{ item.areaName }}</Option
          >
        </Select>
        <Select
          :transfer="true"
          v-model="searchForm.marketid"
          @on-change="marketChange(searchForm.marketid, 1)"
          style="width: 120px"
          placeholder="请选择市"
        >
          <Option
            v-for="item in searchForm.marketList"
            :value="item.areaCode"
            :key="item.areaCode"
            >{{ item.areaName }}</Option
          >
        </Select>
        <Select
          :transfer="true"
          v-model="searchForm.areaCode"
          @on-change="regionChange(1)"
          style="width: 120px; margin: 0 10px"
          placeholder="请选择区"
        >
          <Option
            v-for="item in searchForm.regionList"
            :value="item.areaCode"
            :key="item.areaCode"
            >{{ item.areaName }}</Option
          >
        </Select>
        <Input
          v-model="searchForm.schoolName"
          placeholder="请输入学校名称"
          search
          @on-search="searchList()"
          style="width: 150px"
        />
      </div>
      <Button type="primary" class="primary_btn" @click="toAdd()">新建</Button>
    </div>
    <div class="table_wrap">
      <Table :columns="columns" :data="searchForm.list">
        <template slot-scope="{ row }" slot="enabled">
          <i-switch
            size="large"
            v-model="row.enabled"
            :true-value="1"
            :false-value="2"
            @on-change="enabledChange(row)"
          >
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </template>
        <template slot-scope="{ row }" slot="actionSlot">
          <div class="action_list">
            <div @click="toSchool(row)">进入</div>
            <div @click="toEdit(row)">编辑</div>
            <div class="action_del" @click="toDel(row)">删除</div>
          </div>
        </template>
      </Table>
    </div>
    <div class="page_wrap">
      <Page
        :transfer="true"
        :total="searchForm.total"
        :current="searchForm.page"
        :page-size="searchForm.size"
        :page-size-opts="[10, 20, 40, 60]"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
        show-total
        show-sizer
      ></Page>
    </div>
    <!-- 新建/编辑 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="adminInfo.show"
      :title="adminInfo.schoolid ? '编辑' : '新建'"
    >
      <Form
        v-if="adminInfo.show"
        ref="addForm"
        :model="adminInfo"
        :rules="rules"
        :label-width="110"
        inline
      >
        <FormItem label="学校名称" prop="schoolName" style="width: 100%">
          <Input
            v-model="adminInfo.schoolName"
            placeholder="请输入学校名称"
          ></Input>
        </FormItem>
        <FormItem label="学校简称" style="width: 100%">
          <Input
            v-model="adminInfo.schoolAbbr"
            placeholder="请输入学校简称"
          ></Input>
        </FormItem>
        <FormItem label="省市区" class="require" style="width: 100%">
          <Select
            :transfer="true"
            v-model="adminInfo.provinceid"
            style="width: 120px"
            placeholder="请选择省份"
            @on-change="provinceChange(adminInfo.provinceid, null)"
          >
            <Option
              v-for="item in areaList"
              :value="item.areaCode"
              :key="item.areaCode"
              >{{ item.areaName }}</Option
            >
          </Select>
          <Select
            :transfer="true"
            v-model="adminInfo.marketid"
            @on-change="marketChange(adminInfo.marketid, null)"
            style="width: 120px; margin: 0 10px"
            placeholder="请选择市"
          >
            <Option
              v-for="item in marketList"
              :value="item.areaCode"
              :key="item.areaCode"
              >{{ item.areaName }}</Option
            >
          </Select>
          <Select
            :transfer="true"
            v-model="adminInfo.areaCode"
            style="width: 120px"
            placeholder="请选择区"
          >
            <Option
              v-for="item in regionList"
              :value="item.areaCode"
              :key="item.areaCode"
              >{{ item.areaName }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="地址" style="width: 100%">
          <Input v-model="adminInfo.address" placeholder="请输入地址"></Input>
        </FormItem>
        <FormItem label="所属区域" prop="regionid" style="width: 100%">
          <Select
            :transfer="true"
            v-model="adminInfo.regionid"
            style="width: calc(50% - 65px)"
          >
            <Option
              v-for="item in searchForm.dropList"
              :value="item.regionid"
              :key="item.regionid"
              >{{ item.regionName }}</Option
            >
          </Select>
          <div v-if="!adminInfo.schoolid">
            <Checkbox v-model="adminInfo.createAdmin">创建管理员</Checkbox>
          </div>
        </FormItem>
        <div v-if="adminInfo.createAdmin">
          <FormItem
            label="管理员名称"
            prop="admin.aname"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.admin.aname"
              placeholder="请输入管理员名称"
            ></Input>
          </FormItem>
          <FormItem
            label="登录账号"
            prop="admin.loginname"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.admin.loginname"
              placeholder="请输入登录账号"
            ></Input>
          </FormItem>
          <FormItem
            label="密码"
            prop="admin.loginpwd"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.admin.loginpwd"
              placeholder="请输入密码"
            ></Input>
          </FormItem>
          <FormItem
            label="确认密码"
            prop="admin.loginpwd1"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.admin.loginpwd1"
              placeholder="请输入确认密码"
            ></Input>
          </FormItem>
          <FormItem
            label="手机号码"
            prop="admin.phone"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.admin.phone"
              placeholder="请输入手机号码"
            ></Input>
          </FormItem>
          <FormItem label="短信验证码" style="width: calc(50% - 10px)">
            <Input
              style="width: calc(100% - 102px)"
              v-model="adminInfo.admin.msgcode"
              placeholder="请输入短信验证码"
            ></Input>
            <div
              :class="['code_btn', adminInfo.second === 60 ? '' : 'disabled']"
              @click="getMsgCode()"
            >
              {{
                adminInfo.second === 60 ? "获取验证码" : `${adminInfo.second}s`
              }}
            </div>
          </FormItem>
        </div>
      </Form>
      <div
        slot="footer"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="color: #b50000">
          注：密码必须包含大小写字母和数字的组合，长度在8-32之间。
        </div>
        <div>
          <Button @click="adminInfo.show = false">取消</Button>
          <Button @click="saveAddInfo()" type="primary">保存</Button>
        </div>
      </div>
    </Modal>
    <!-- 查看 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="viewInfo.show"
      title="查看"
    >
      <div class="view_title">
        <div>{{ viewInfo.aname }}</div>
        <div v-if="viewInfo.enabled === 1" class="enabled_1">启用</div>
        <div v-if="viewInfo.enabled === 2" class="enabled_2">禁用</div>
      </div>
      <Form :label-width="80" inline>
        <FormItem
          label="登录账号"
          style="margin-bottom: 0; width: calc(50% - 10px)"
          >{{ viewInfo.loginname }}</FormItem
        >
        <FormItem
          label="手机号码"
          style="margin-bottom: 0; width: calc(50% - 10px)"
          >{{ viewInfo.phone }}</FormItem
        >
        <FormItem label="所属区域" style="margin-bottom: 0; width: 100%">{{
          viewInfo.regionName
        }}</FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { region_list_sel_pt } from "@/api/region";
import { login_msg_code } from "@/api/login";
import { generateRandomString } from "@/utils";
import {
  area_list_sel,
  school_add,
  school_delete,
  school_detail,
  school_disabled,
  school_edit,
  school_enable,
  school_list
} from "@/api/school";
export default {
  data() {
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,32}$/;
    // 密码验证
    const pwdCheck = (rule, value, callback) => {
      if (!reg.test(this.adminInfo.admin.loginpwd)) {
        return callback(new Error("密码格式不正确!"));
      } else {
        callback();
      }
    };
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (!reg.test(this.adminInfo.admin.loginpwd1)) {
        return callback(new Error("密码格式不正确!"));
      } else if (
        this.adminInfo.admin.loginpwd != this.adminInfo.admin.loginpwd1
      ) {
        return callback(new Error("两次输入密码不一致！"));
      } else {
        callback();
      }
    };
    return {
      searchForm: {
        dropList: [],
        marketList: [],
        regionList: [],
        provinceid: "",
        marketid: "",
        areaCode: "",
        regionid: 0, // 0所有区域
        schoolName: "",
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      // 新建/编辑
      adminInfo: {
        show: false,
        timer: null,
        second: 60,
        schoolid: null,
        schoolName: "",
        areaCode: "",
        areaName: "",
        address: "",
        schoolAbbr: "",
        regionid: null,
        createAdmin: false,
        admin: {
          aname: "",
          loginname: "",
          loginpwd: "",
          phone: "",
          msgcode: ""
        }
      },
      rules: {
        schoolName: [
          {
            required: true,
            message: "请输入学校名称",
            trigger: "blur"
          }
        ],
        "admin.aname": [
          {
            required: true,
            message: "请输入管理员名称",
            trigger: "blur"
          }
        ],
        "admin.loginname": [
          {
            required: true,
            message: "请输入请输入登录账号",
            trigger: "blur"
          }
        ],
        "admin.loginpwd": [
          {
            required: true,
            validator: pwdCheck,
            trigger: "blur"
          }
        ],
        "admin.loginpwd1": [
          {
            required: true,
            validator: pwdAgainCheck,
            trigger: "blur"
          }
        ]
      },
      // 查看
      viewInfo: {
        show: false,
        enabled: "",
        aname: "",
        loginname: "",
        phone: "",
        regionName: ""
      },
      columns: [
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        {
          title: "学校名称",
          key: "schoolName",
          align: "center"
        },
        {
          title: "状态",
          slot: "enabled",
          align: "center",
          width: 80
        },
        {
          title: "设备数",
          key: "devicenum",
          width: 80,
          align: "center"
        },
        {
          title: "省市区",
          key: "areaName",
          align: "center"
        },
        {
          title: "所属区域",
          key: "regionName",
          width: 150,
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          width: 150,
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 180,
          align: "center"
        }
      ],
      areaList: [],
      marketList: [],
      regionList: [],
      userInfo: {}
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.getSearchRegionList();
    this.getAreaList();
    this.searchList();
  },
  mounted() {},
  methods: {
    //选择省份
    provinceChange(id, type) {
      let arr = this.areaList.filter((v) => v.areaCode === id);
      if (type) {
        this.searchForm.marketList = arr[0].childList;
        this.searchForm.marketid = "";
        this.searchForm.regionList = [];
        this.searchForm.areaCode = "";
        this.searchList(arr[0]);
      } else {
        this.marketList = arr[0].childList;
        this.adminInfo.marketid = "";
        this.regionList = [];
        this.adminInfo.areaCode = "";
      }
    },
    //选择市
    marketChange(id, type) {
      if (!id) {
        return;
      }
      if (type) {
        let arr = this.searchForm.marketList.filter((v) => v.areaCode === id);
        this.searchForm.regionList = arr[0].childList;
        this.searchForm.areaCode = "";
        this.searchList(arr[0]);
      } else {
        let arr = this.marketList.filter((v) => v.areaCode === id);
        this.regionList = arr[0].childList;
        this.adminInfo.areaCode = "";
      }
    },
    //选中区
    regionChange() {
      if (!this.searchForm.areaCode) {
        return;
      }
      this.searchList();
    },
    getAreaList() {
      area_list_sel({}).then((res) => {
        if (res.code === 0) {
          this.areaList = res.obj;
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 获取搜索区域列表
    getSearchRegionList() {
      region_list_sel_pt({}).then((data) => {
        if (data.code === 0) {
          this.searchForm.dropList = data.obj;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 搜索
    searchList(obj) {
      this.searchForm.page = 1;
      this.getList(obj);
    },
    // 页码改变
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },
    // 每页显示数量改变
    pageSizeChange(size) {
      this.searchForm.size = size;
      this.searchForm.page = 1;
      this.getList();
    },
    // 获取列表
    getList(obj) {
      school_list({
        page: this.searchForm.page,
        size: this.searchForm.size,
        areaCode: obj && obj.areaCode?obj.areaCode:this.searchForm.areaCode,
        schoolName: this.searchForm.schoolName,
        regionid: this.searchForm.regionid
      }).then((data) => {
        if (data.code === 0) {
          this.searchForm.list = data.obj.data;
          this.searchForm.total = data.obj.total;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 新建
    toAdd() {
      this.adminInfo = {
        show: true,
        timer: null,
        second: 60,
        schoolid: null,
        schoolName: "",
        provinceid: "",
        marketid: "",
        areaCode: "",
        areaName: "",
        address: "",
        schoolAbbr: "",
        regionid: this.userInfo.regionid,
        createAdmin: false,
        admin: {
          aname: "",
          loginname: "",
          loginpwd: generateRandomString(8),
          loginpwd1: "",
          phone: "",
          msgcode: ""
        }
      };
    },
    // 获取短信验证码
    getMsgCode() {
      if (this.adminInfo.second < 60) {
        return;
      }
      // 手机号验证
      if (!this.adminInfo.admin.phone) {
        this.$Message.error("手机号码不能为空");
        return;
      }
      let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!filter.test(this.adminInfo.admin.phone)) {
        this.$Message.error("手机号码格式不正确");
        return;
      }
      this.setRegionSecond();
      login_msg_code({
        phone: this.adminInfo.admin.phone
      }).then((data) => {
        if (data.code === 0) {
          this.$Message.success(data.msg);
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    setRegionSecond() {
      this.adminInfo.second = 59;
      this.adminInfo.timer = setInterval(() => {
        this.adminInfo.second--;
        if (this.adminInfo.second <= 0) {
          clearInterval(this.adminInfo.timer);
          this.adminInfo.timer = null;
          this.adminInfo.second = 60;
        }
      }, 1000);
    },
    // 保存新建
    saveAddInfo() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          //添加学校管理员
          if (this.adminInfo.createAdmin) {
            if (
              this.adminInfo.admin.loginpwd != this.adminInfo.admin.loginpwd1
            ) {
              this.$Message.error("两次输入密码不一致！");
              return;
            }
            let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
            if (
              this.adminInfo.admin.phone &&
              !filter.test(this.adminInfo.admin.phone)
            ) {
              this.$Message.error("手机号码格式不正确");
              return;
            }
            if (this.adminInfo.admin.phone && !this.adminInfo.admin.msgcode) {
              this.$Message.error("请输入短信验证码");
              return;
            }
            if (this.adminInfo.timer) {
              clearInterval(this.adminInfo.timer);
              this.adminInfo.timer = null;
            }
          }
          let areaObj = this.regionList.filter(
            (v) => v.areaCode === this.adminInfo.areaCode
          )[0];
          this.adminInfo.areaName = areaObj.areaAll;
          this.adminInfo.show = false;
          let api = this.adminInfo.schoolid ? school_edit : school_add;
          let form = {
            schoolName: this.adminInfo.schoolName,
            regionid: this.adminInfo.regionid,
            areaCode: this.adminInfo.areaCode,
            areaName: this.adminInfo.areaName,
            address: this.adminInfo.address,
            schoolAbbr: this.adminInfo.schoolAbbr,
            admin: {}
          };
          //编辑
          if (this.adminInfo.schoolid) {
            form.schoolid = this.adminInfo.schoolid;
            form.rversion = this.adminInfo.rversion;
          }
          //添加管理员
          if (this.adminInfo.createAdmin) {
            form.admin = {
              aname: this.adminInfo.admin.aname,
              loginname: this.adminInfo.admin.loginname,
              loginpwd: this.adminInfo.admin.loginpwd,
              phone: this.adminInfo.admin.phone,
              msgcode: this.adminInfo.admin.msgcode
            };
          }
          api(form).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 进入学校
    toSchool(row) {},
    // 编辑
    toEdit(row) {
      school_detail({ schoolid: row.schoolid }).then((res) => {
        if (res.code === 0) {
          let str = res.obj.areaCode;
          //获取省市区
          let obj1 = this.areaList.filter((v) =>
            v.areaCode.includes(str.substring(0, 2))
          )[0];
          this.marketList = obj1.childList;
          let obj2 = obj1.childList.filter((v) =>
            v.areaCode.includes(str.substring(0, 4))
          )[0];
          this.regionList = obj2.childList;
          this.adminInfo = {
            show: true,
            timer: null,
            second: 0,
            schoolid: res.obj.schoolid,
            schoolName: res.obj.schoolName,
            provinceid: obj1.areaCode,
            marketid: obj2.areaCode,
            areaCode: res.obj.areaCode,
            areaName: res.obj.areaName,
            address: res.obj.address,
            schoolAbbr: res.obj.schoolAbbr,
            regionid: res.obj.regionid,
            rversion: res.obj.rversion,
            createAdmin: false,
            admin: {}
          };
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          school_delete({
            schoolid: row.schoolid,
            rversion: row.rversion
          }).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        },
        onCancel: () => {}
      });
    },
    enabledChange(row) {
      let api = row.enabled === 1 ? school_enable : school_disabled;
      api({
        schoolid: row.schoolid,
        rversion: row.rversion
      }).then((data) => {
        this.getList();
        if (data.code === 0) {
          this.$Message.success(data.msg);
        } else {
          this.$Message.error(data.msg);
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.search_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 16px;
  .search_left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
}
.code_btn {
  display: inline-block;
  margin-left: 10px;
  width: 92px;
  font-size: 14px;
  text-align: center;
  color: #339dff;
  line-height: 30px;
  border: 1px solid #339dff;
  border-radius: 6px;
  background-color: #fff;
  cursor: pointer;
  &.disabled {
    color: #c5c8ce;
    background-color: #f7f7f7;
    border-color: #dcdee2;
    cursor: not-allowed;
  }
}
.view_title {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  .enabled_1 {
    margin-left: 10px;
    padding: 0 10px;
    line-height: 20px;
    color: #52c41a;
    font-weight: normal;
    font-size: 12px;
    border-radius: 4px;
    background-color: #eefae9;
  }
  .enabled_2 {
    margin-left: 10px;
    padding: 0 10px;
    line-height: 20px;
    color: #f0153f;
    font-weight: normal;
    font-size: 12px;
    border-radius: 4px;
    background-color: #fee8ec;
  }
}
</style>
