<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="actionSlot">
          <div class="action_list">
            <div @click="toEnter(row)">进入</div>
            <div @click="toView(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="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="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>
      </Form>
      <div
        slot="footer"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="color: #b50000">
          注：密码必须包含大小写字母和数字的组合，长度在8-32之间。
        </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>
      </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>
      <Table
        style="border: 1px solid #e8eaec; border-bottom: none"
        :columns="viewInfo.columns"
        :data="viewInfo.list"
      ></Table>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { generateRandomString } from "@/utils";
import {
  region_list_admin,
  region_delete,
  region_add,
  region_edit,
  region_list_qy,
  region_detail
} from "@/api/region";
import { login_msg_code } from "@/api/login";
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.regionInfo.admin.loginpwd)) {
        return callback(new Error("密码格式不正确!"));
      }
    };
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (!reg.test(this.regionInfo.admin.loginpwd1)) {
        return callback(new Error("密码格式不正确!"));
      }
      if (this.regionInfo.admin.loginpwd != this.regionInfo.admin.loginpwd1) {
        return callback(new Error("两次输入密码不一致！"));
      }
    };
    return {
      searchForm: {
        regionName: "",
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      // 新建
      regionInfo: {
        show: false,
        // 验证码计时
        timer: null,
        second: 60,
        regionName: "",
        admin: {
          aname: "",
          loginname: "",
          loginpwd: "",
          loginpwd1: "",
          phone: "",
          msgcode: ""
        }
      },
      // 编辑
      modifyRegion: {
        show: false,
        regionid: null,
        regionName: "",
        rversion: null
      },
      // 查看
      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"
          }
        ]
      },
      rules: {
        regionName: [
          {
            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"
          }
        ]
      },
      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: "createname",
          width: 140,
          align: "center"
        },
        {
          title: "创建时间",
          key: "createtime",
          width: 190,
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          width: 140,
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 220,
          align: "center"
        }
      ]
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.searchList();
  },
  methods: {
    // 获取短信验证码
    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.setRegionSecond();
      login_msg_code({
        phone: this.regionInfo.admin.phone
      }).then((data) => {
        if (data.code === 0) {
          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() {
      region_list_qy({
        page: this.searchForm.page,
        size: this.searchForm.size,
        regionName: this.searchForm.regionName,
        regionid: this.userInfo.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() {
      if (this.regionInfo.timer) {
        clearInterval(this.regionInfo.timer);
        this.regionInfo.timer = null;
      }
      this.regionInfo = {
        show: true,
        // 验证码计时
        timer: null,
        second: 60,
        regionName: "",
        admin: {
          aname: "",
          loginname: "",
          loginpwd: generateRandomString(8),
          loginpwd1: "",
          phone: "",
          msgcode: ""
        }
      };
    },
    // 保存新建
    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.regionInfo.show = false;
          region_add({
            regionName: this.regionInfo.regionName,
            regionPid: this.userInfo.regionid,
            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
            }
          }).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 保存编辑
    saveModifyInfo() {
      this.$refs.modifyForm.validate((valid) => {
        if (valid) {
          region_edit({
            regionName: this.modifyRegion.regionName,
            regionid: this.modifyRegion.regionid,
            rversion: this.modifyRegion.rversion
          }).then((data) => {
            this.modifyRegion.show = false;
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 进入
    toEnter() {
      this.$router.push({
        path: "/region/home",
        query: {}
      });
    },
    // 查看管理员列表
    toView(row) {
      region_list_admin({
        regionid: row.regionid
      }).then((data) => {
        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) {
      region_detail({ regionid: row.regionid }).then((res) => {
        if (res.code === 0) {
          this.modifyRegion = {
            show: true,
            regionid: row.regionid,
            regionName: row.regionName,
            rversion: row.rversion
          };
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          region_delete({
            regionid: row.regionid,
            rversion: row.rversion
          }).then((data) => {
            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;
}
</style>
