<template>
  <div class="main_root">
    <div class="search_header">
      <Input
        v-model="searchForm.regionName"
        placeholder="请输入区域名称"
        search
        @on-search="searchList()"
        style="width: 150px"
      />
      <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="sso">
          <span>{{ row.sso === 1 ? "平台" : "单点登录" }}</span>
        </template>
        <template slot-scope="{ row }" slot="actionSlot">
          <div class="action_list">
            <div
              v-if="row.regionid != powerParams.objectid"
              @click="toEnter(row)"
            >
              进入
            </div>
            <div @click="toView(row)">查看</div>
            <div @click="toEdit(row)">编辑</div>
            <div
              v-if="row.regionid != powerParams.objectid"
              class="action_del"
              @click="toDel(row)"
            >
              删除
            </div>
            <div @click="toSet(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="regionInfo.show"
      title="新建"
    >
      <Form
        v-if="regionInfo.show"
        ref="addForm"
        :model="regionInfo"
        :rules="rules"
        :label-width="110"
        inline
      >
        <FormItem label="区域名称" prop="regionName" style="width: 100%">
          <Input
            v-model="regionInfo.regionName"
            placeholder="请输入区域名称"
          ></Input>
        </FormItem>
        <FormItem label="区域码" prop="regionCode" style="width: 100%">
          <Input
            v-model="regionInfo.regionCode"
            placeholder="请输入六位区域码"
            :maxlength="6"
          ></Input>
        </FormItem>
        <FormItem
          label="管理员名称"
          prop="admin.aname"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="regionInfo.admin.aname"
            placeholder="请输入管理员名称"
          ></Input>
        </FormItem>
        <FormItem
          label="登录账号"
          prop="admin.loginname"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="regionInfo.admin.loginname"
            placeholder="请输入登录账号"
          ></Input>
        </FormItem>
        <FormItem
          label="密码"
          prop="admin.loginpwd"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="regionInfo.admin.loginpwd"
            placeholder="请输入密码"
          ></Input>
        </FormItem>
        <FormItem
          label="确认密码"
          prop="admin.loginpwd1"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="regionInfo.admin.loginpwd1"
            placeholder="请输入确认密码"
          ></Input>
        </FormItem>
        <FormItem label="手机号码" style="width: calc(50% - 10px)">
          <Input
            v-model="regionInfo.admin.phone"
            placeholder="请输入手机号码"
          ></Input>
        </FormItem>
        <FormItem label="短信验证码" style="width: calc(50% - 10px)">
          <Input
            style="width: calc(100% - 102px)"
            v-model="regionInfo.admin.msgcode"
            placeholder="请输入短信验证码"
          ></Input>
          <div
            :class="['code_btn', regionInfo.second === 60 ? '' : 'disabled']"
            @click="getMsgCode()"
          >
            {{
              regionInfo.second === 60 ? "获取验证码" : `${regionInfo.second}s`
            }}
          </div>
        </FormItem>
        <FormItem label="地址" style="width: 100%">
          <Input
            v-model="regionInfo.admin.address"
            placeholder="请输入地址"
          ></Input>
        </FormItem>
        <FormItem label="描述信息" style="width: 100%">
          <Input
            type="textarea"
            v-model="regionInfo.admin.comm"
            placeholder="请输入描述信息"
          ></Input>
        </FormItem>
      </Form>
      <div
        slot="footer"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="color: #b50000">
          注：密码必须是6-16位的大小写英文字母、数字组合。
        </div>
        <div>
          <Button @click="regionInfo.show = false">取消</Button>
          <Button @click="saveAddInfo()" type="primary">保存</Button>
        </div>
      </div>
    </Modal>
    <!-- 编辑 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="modifyRegion.show"
      title="编辑"
    >
      <Form
        v-if="modifyRegion.show"
        ref="modifyForm"
        :model="modifyRegion"
        :rules="rules"
        :label-width="90"
        inline
      >
        <FormItem label="区域名称" prop="regionName" style="width: 100%">
          <Input
            v-model="modifyRegion.regionName"
            placeholder="请输入区域名称"
          ></Input>
        </FormItem>
        <FormItem label="区域码" prop="regionCode" style="width: 100%">
          <Input
            v-model="modifyRegion.regionCode"
            placeholder="请输入六位区域码"
            :maxlength="6"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modifyRegion.show = false">取消</Button>
        <Button @click="saveModifyInfo()" type="primary">保存</Button>
      </div>
    </Modal>
    <!-- 查看 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="viewInfo.show"
      title="查看"
    >
      <div class="view_title">{{ viewInfo.regionName }}</div>
      <div class="table_wrap">
        <Table :columns="viewInfo.columns" :data="viewInfo.list"></Table>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
    <!-- 设置 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="authInfo.show"
      title="设置"
    >
      <div v-if="authInfo.show">
        <Form
          ref="authInfo"
          :model="authInfo"
          :rules="rules1"
          :label-width="110"
        >
          <FormItem label="单点登录" prop="sso" class="require">
            <RadioGroup v-model="authInfo.sso">
              <Radio :label="1">平台</Radio>
              <Radio :label="2">自定义</Radio>
            </RadioGroup>
          </FormItem>
          <div class="platformLogin" v-if="authInfo.sso === 1">
            <img src="../../../assets/img/platformLogin.png" />
            <p>当前已选择平台登录</p>
          </div>
          <div v-else>
            <FormItem label="认证地址" prop="authUrl">
              <Input
                v-model.trim="authInfo.authUrl"
                placeholder="请输入认证地址"
              ></Input>
            </FormItem>
            <FormItem label="认证密钥" prop="authKey">
              <Input
                v-model.trim="authInfo.authKey"
                placeholder="请输入认证密钥"
              ></Input>
            </FormItem>
            <FormItem label="认证类型" class="require">
              <RadioGroup v-model="authInfo.authType">
                <Radio :label="1">账号</Radio>
                <Radio :label="2">学号</Radio>
                <Radio :label="3">手机号码</Radio>
                <Radio :label="4">身份证号码</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="请求说明">
              <div class="table_wrap" style="margin: 0">
                <Table :columns="columns1" :data="request_list"></Table>
              </div>
            </FormItem>
            <FormItem label="返回说明">
              <div style="line-height: 36px; margin-bottom: 10px">
                以json格式返回数据
              </div>
              <div class="table_wrap" style="margin: 0">
                <Table
                  row-key="id"
                  :columns="columns1"
                  :data="response_list"
                ></Table>
              </div>
            </FormItem>
          </div>
        </Form>
      </div>
      <div slot="footer" style="text-align: right">
        <Button @click="authInfo.show = false">关闭</Button>
        <Button @click="saveauthInfo()" 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 { codeCheck, generateRandomString, pwdCheck, reg } from "@/utils";
import {
  region_list_admin,
  region_delete,
  region_add,
  region_edit,
  region_list_qy,
  region_detail,
  region_set
} from "@/api/region";
import { login_msg_code } from "@/api/login";
export default {
  data() {
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (!reg.test(value)) {
        return callback(new Error("密码格式不正确!"));
      }
      if (this.regionInfo.admin.loginpwd != value) {
        return callback(new Error("两次输入密码不一致！"));
      }
      callback();
    };
    return {
      showLoading: false,
      searchForm: {
        regionName: "",
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      // 新建
      regionInfo: {
        show: false,
        // 验证码计时
        timer: null,
        second: 60,
        regionName: "",
        regionCode: "",
        admin: {
          aname: "",
          loginname: "",
          loginpwd: "",
          loginpwd1: "",
          phone: "",
          msgcode: "",
          address: "",
          comm: ""
        }
      },
      // 编辑
      modifyRegion: {
        show: false,
        regionid: null,
        regionName: "",
        regionCode: "",
        rversion: null,
        address: "",
        comm: ""
      },
      // 查看
      viewInfo: {
        show: false,
        regionName: "",
        list: [],
        columns: [
          {
            title: "序号",
            type: "index",
            width: 70,
            align: "center"
          },
          {
            title: "名称",
            key: "aname",
            align: "center"
          },
          {
            title: "账号",
            key: "loginname",
            align: "center"
          },
          {
            title: "手机号码",
            key: "phone",
            align: "center"
          }
        ]
      },
      authInfo: {
        show: false,
        regionid: null,
        rversion: null,
        sso: null,
        authUrl: null,
        authKey: null,
        authType: null
      },
      rules1: {
        authUrl: [
          {
            required: true,
            message: "请输入认证地址",
            trigger: "blur"
          }
        ],
        authKey: [
          {
            required: true,
            message: "请输入认证密钥",
            trigger: "blur"
          }
        ]
      },
      rules: {
        regionName: [
          {
            required: true,
            message: "请输入区域名称",
            trigger: "blur"
          }
        ],
        regionCode: [
          {
            required: true,
            validator: codeCheck,
            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"
          }
        ]
      },
      columns: [
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        {
          title: "区域名称",
          key: "regionName",
          align: "center"
        },
        {
          title: "区域码",
          key: "regionCode",
          align: "center"
        },
        {
          title: "登录类型",
          slot: "sso",
          align: "center"
        },
        {
          title: "创建人",
          key: "createname",
          align: "center"
        },
        {
          title: "创建时间",
          key: "createtime",
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 230,
          align: "center"
        }
      ],
      columns1: [
        {
          title: "参数",
          key: "data",
          align: "center",
          width: 180,
          tree: true
        },
        {
          title: "类型",
          key: "type",
          width: 120,
          align: "center"
        },
        {
          title: "是否必填",
          key: "Required",
          width: 120,
          align: "center"
        },
        {
          title: "说明",
          key: "comm",
          align: "center"
        }
      ],
      request_list: [
        {
          data: "authKey",
          type: "string",
          Required: "是",
          comm: "认证秘钥"
        },
        {
          data: "authType",
          type: "int",
          Required: "是",
          comm: "认证类型：1账号2学号3手机号码4身份证号"
        },
        {
          data: "timestamp",
          type: "int",
          Required: "是",
          comm: "当前时间戳"
        },
        {
          data: "loginname",
          type: "string",
          Required: "是",
          comm: "认证类型对应的值"
        },
        {
          data: "loginpwd",
          type: "string",
          Required: "是",
          comm: "认证密码"
        },
        {
          data: "sign",
          type: "string",
          Required: "是",
          comm: "签名"
        },
        {
          data: "mac",
          type: "string",
          Required: "是",
          comm: "设备"
        }
      ],
      response_list: [
        {
          id: 1,
          data: "code",
          type: "int",
          Required: "是",
          comm: "0正常，1错误"
        },
        {
          id: 2,
          data: "msg",
          type: "string",
          Required: "是",
          comm: "成功/失败(有失败信息)"
        },
        {
          id: 3,
          data: "obj",
          type: "object",
          Required: "是",
          comm: "用户信息",
          children: [
            {
              id: 4,
              data: "schoolid",
              type: "int",
              Required: "是",
              comm: "学校ID"
            },
            {
              id: 5,
              data: "schoolName",
              type: "string",
              Required: "是",
              comm: "学校名称"
            },
            {
              id: 6,
              data: "classid",
              type: "int",
              Required: "是",
              comm: "班级ID"
            },
            {
              id: 7,
              data: "classname",
              type: "string",
              Required: "是",
              comm: "班级名称"
            },
            {
              id: 8,
              data: "userid",
              type: "int",
              Required: "是",
              comm: "用户ID"
            },
            {
              id: 9,
              data: "usename",
              type: "string",
              Required: "是",
              comm: "用户姓名"
            },
            {
              id: 10,
              data: "userphone",
              type: "string",
              Required: "是",
              comm: "手机号码"
            },
            {
              id: 11,
              data: "studentno",
              type: "string",
              Required: "是",
              comm: "学号"
            },
            {
              id: 12,
              data: "loginname",
              type: "string",
              Required: "是",
              comm: "账号"
            },
            {
              id: 13,
              data: "cardid",
              type: "string",
              Required: "是",
              comm: "身份证号"
            },
            {
              id: 14,
              data: "usersex",
              type: "int",
              Required: "是",
              comm: "性别0未知1男2女"
            }
          ]
        }
      ]
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.searchList();
  },
  computed: {
    powerParams() {
      return this.$store.getters.powerParams;
    }
  },
  methods: {
    toSet(row) {
      this.authInfo = {
        show: true,
        regionid: row.regionid,
        rversion: row.rversion,
        sso: row.sso || 1,
        authUrl: row.authUrl,
        authKey: row.authKey,
        authType: row.authType
      };
    },
    // 获取短信验证码
    getMsgCode() {
      if (this.regionInfo.second < 60) {
        return;
      }
      // 手机号验证
      if (!this.regionInfo.admin.phone) {
        this.$Message.error("手机号码不能为空");
        return;
      }
      let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!filter.test(this.regionInfo.admin.phone)) {
        this.$Message.error("手机号码格式不正确");
        return;
      }
      this.showLoading = true;
      login_msg_code({
        phone: this.regionInfo.admin.phone
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.setRegionSecond();
          this.$Message.success(data.msg);
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    setRegionSecond() {
      this.regionInfo.second = 59;
      this.regionInfo.timer = setInterval(() => {
        this.regionInfo.second--;
        if (this.regionInfo.second === 0) {
          clearInterval(this.regionInfo.timer);
          this.regionInfo.timer = null;
          this.regionInfo.second = 60;
        }
      }, 1000);
    },
    // 搜索
    searchList() {
      this.searchForm.page = 1;
      this.getList();
    },
    // 页码改变
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },
    // 每页显示数量改变
    pageSizeChange(size) {
      this.searchForm.size = size;
      this.searchForm.page = 1;
      this.getList();
    },
    // 获取列表
    getList() {
      this.showLoading = true;
      region_list_qy({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        regionid: this.powerParams.objectid,
        page: this.searchForm.page,
        size: this.searchForm.size,
        regionName: this.searchForm.regionName
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.searchForm.list = data.obj.data;
          this.searchForm.total = data.obj.total;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 新建
    toAdd() {
      if (this.regionInfo.timer) {
        clearInterval(this.regionInfo.timer);
      }
      this.regionInfo = {
        show: true,
        // 验证码计时
        timer: null,
        second: 60,
        regionName: "",
        regionCode: "",
        admin: {
          aname: "",
          loginname: "",
          loginpwd: generateRandomString(),
          loginpwd1: "",
          phone: "",
          msgcode: "",
          address: "",
          comm: ""
        }
      };
    },
    //设置
    saveauthInfo() {
      this.$refs.authInfo.validate((valid) => {
        if (valid) {
          if (!this.authInfo.sso) {
            this.$Message.error("请选择登录方式!");
            return;
          }
          let form = {
            sso: this.authInfo.sso,
            regionid: this.authInfo.regionid,
            rversion: this.authInfo.rversion
          };
          if (form.sso === 2) {
            form.authUrl = this.authInfo.authUrl;
            form.authKey = this.authInfo.authKey;
            form.authType = this.authInfo.authType;
          }
          this.showLoading = true;
          region_set(form).then((data) => {
            this.showLoading = false;
            this.authInfo.show = false;
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 保存新建
    saveAddInfo() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          if (
            this.regionInfo.admin.phone &&
            !filter.test(this.regionInfo.admin.phone)
          ) {
            this.$Message.error("手机号码格式不正确");
            return;
          }
          if (this.regionInfo.admin.phone && !this.regionInfo.admin.msgcode) {
            this.$Message.error("请输入短信验证码");
            return;
          }
          if (this.regionInfo.timer) {
            clearInterval(this.regionInfo.timer);
            this.regionInfo.timer = null;
          }
          this.showLoading = true;
          region_add({
            regionName: this.regionInfo.regionName,
            rtype: this.powerParams.rtype,
            objectid: this.powerParams.objectid,
            regionPid: this.powerParams.objectid,
            regionCode: this.regionInfo.regionCode,
            admin: {
              aname: this.regionInfo.admin.aname,
              loginname: this.regionInfo.admin.loginname,
              loginpwd: this.regionInfo.admin.loginpwd,
              phone: this.regionInfo.admin.phone,
              msgcode: this.regionInfo.admin.msgcode,
              address: this.regionInfo.admin.address,
              comm: this.regionInfo.admin.comm
            }
          }).then((data) => {
            this.showLoading = false;
            if (data.code === 0) {
              this.regionInfo.show = false;
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 保存编辑
    saveModifyInfo() {
      this.$refs.modifyForm.validate((valid) => {
        if (valid) {
          this.showLoading = true;
          region_edit({
            rtype: this.powerParams.rtype,
            objectid: this.powerParams.objectid,
            regionid: this.modifyRegion.regionid,
            regionCode: this.modifyRegion.regionCode,
            regionName: this.modifyRegion.regionName,
            rversion: this.modifyRegion.rversion
          }).then((data) => {
            this.showLoading = false;
            this.modifyRegion.show = false;
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 进入
    toEnter(row) {
      this.$store.commit("setEnterRegionPower", {
        regionid: row.regionid,
        regionName: row.regionName
      });
      this.$router.push({
        path: "/region/home",
        query: {}
      });
    },
    // 查看管理员列表
    toView(row) {
      this.showLoading = true;
      region_list_admin({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        regionid: row.regionid
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.viewInfo.show = true;
          this.viewInfo.regionName = row.regionName;
          this.viewInfo.list = data.obj;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 编辑
    toEdit(row) {
      this.showLoading = true;
      region_detail({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        regionid: row.regionid
      }).then((res) => {
        this.showLoading = false;
        if (res.code === 0) {
          this.modifyRegion = {
            show: true,
            regionid: row.regionid,
            regionName: row.regionName,
            regionCode: res.obj.regionCode,
            rversion: row.rversion
          };
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          this.showLoading = true;
          region_delete({
            rtype: this.powerParams.rtype,
            objectid: this.powerParams.objectid,
            regionid: row.regionid,
            rversion: row.rversion
          }).then((data) => {
            this.showLoading = false;
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        },
        onCancel: () => {}
      });
    }
  }
};
</script>

<style lang="less" scoped>
.search_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 16px;
}
.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 {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
.platformLogin {
  text-align: center;
  padding-bottom: 40px;
  img {
    width: 212px;
    height: 212px;
    margin: 0 auto;
    object-fit: cover;
  }
  p {
    line-height: 30px;
    font-size: 14px;
    color: #7c8db5;
  }
}
</style>
