<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.enabled"
          @on-change="searchList()"
          style="margin-right: 10px; width: 150px"
        >
          <Option :value="0">所有状态</Option>
          <Option :value="1">启用</Option>
          <Option :value="2">禁用</Option>
        </Select>
        <Input
          v-model="searchForm.aname"
          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="enabledSlot">
          <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="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="adminInfo.show"
      :title="adminInfo.adminid ? '编辑' : '新建'"
    >
      <Form
        v-if="adminInfo.show"
        ref="addForm"
        :model="adminInfo"
        :rules="rules"
        :label-width="110"
        inline
      >
        <FormItem label="管理员名称" prop="aname" style="width: 100%">
          <Input
            v-model="adminInfo.aname"
            placeholder="请输入管理员名称"
          ></Input>
        </FormItem>
        <FormItem label="登录账号" prop="loginname" style="width: 100%">
          <Input
            v-model="adminInfo.loginname"
            placeholder="请输入登录账号"
          ></Input>
        </FormItem>
        <template v-if="!adminInfo.adminid">
          <FormItem
            label="密码"
            prop="loginpwd"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.loginpwd"
              placeholder="请输入密码"
            ></Input>
          </FormItem>
          <FormItem
            label="确认密码"
            prop="loginpwd1"
            style="width: calc(50% - 10px)"
          >
            <Input
              v-model="adminInfo.loginpwd1"
              placeholder="请输入确认密码"
            ></Input>
          </FormItem>
        </template>
        <template v-else>
          <FormItem label="密码" style="width: calc(50% - 10px)">
            <Input
              v-model="adminInfo.loginpwd"
              placeholder="请输入密码"
            ></Input>
          </FormItem>
          <FormItem label="确认密码" style="width: calc(50% - 10px)">
            <Input
              v-model="adminInfo.loginpwd1"
              placeholder="请输入确认密码"
            ></Input>
          </FormItem>
        </template>
        <FormItem label="手机号码" prop="phone" style="width: calc(50% - 10px)">
          <Input v-model="adminInfo.phone" placeholder="请输入手机号码"></Input>
        </FormItem>
        <FormItem label="短信验证码" style="width: calc(50% - 10px)">
          <Input
            style="width: calc(100% - 102px)"
            v-model="adminInfo.msgcode"
            placeholder="请输入短信验证码"
          ></Input>
          <div
            :class="['code_btn', adminInfo.second === 60 ? '' : 'disabled']"
            @click="getMsgCode()"
          >
            {{
              adminInfo.second === 60 ? "获取验证码" : `${adminInfo.second}s`
            }}
          </div>
        </FormItem>
        <FormItem label="状态" prop="enabled" style="width: 100%">
          <RadioGroup v-model="adminInfo.enabled">
            <Radio :label="1">启用</Radio>
            <Radio :label="2">禁用</Radio>
          </RadioGroup>
        </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>
        </FormItem>
        <FormItem label="地址" prop="address" style="width: 100%">
          <Input v-model="adminInfo.address" placeholder="请输入地址"></Input>
        </FormItem>
        <FormItem label="描述信息" prop="comm" style="width: 100%">
          <Input
            type="textarea"
            v-model="adminInfo.comm"
            placeholder="请输入描述信息"
          ></Input>
        </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="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>
        <FormItem label="地址" style="margin-bottom: 0; width: 100%">{{
          viewInfo.address
        }}</FormItem>
        <FormItem label="描述信息" style="margin-bottom: 0; width: 100%">{{
          viewInfo.comm
        }}</FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  admin_list_pt,
  admin_add,
  admin_edit,
  admin_delete,
  admin_enable,
  admin_disabled
} from "@/api/admin";
import { region_list_sel_pt } from "@/api/region";
import { login_msg_code } from "@/api/login";
import { generateRandomString } from "@/utils";
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.loginpwd)) {
        return callback(
          new Error("密码必须包含大小写字母和数字的组合，长度在8-32之间。")
        );
      } else {
        callback();
      }
    };
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (!reg.test(this.adminInfo.loginpwd1)) {
        return callback(
          new Error("密码必须包含大小写字母和数字的组合，长度在8-32之间。")
        );
      } else if (this.adminInfo.loginpwd != this.adminInfo.loginpwd1) {
        return callback(new Error("两次输入密码不一致！"));
      } else {
        callback();
      }
    };
    return {
      searchForm: {
        dropList: [],
        aname: "",
        // 0所有区域
        regionid: 0,
        // 是否启用0所有 1启用 2禁用
        enabled: 0,
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      rules: {
        regionName: [
          {
            required: true,
            message: "请输入区域名称",
            trigger: "blur"
          }
        ],
        aname: [
          {
            required: true,
            message: "请输入管理员名称",
            trigger: "blur"
          }
        ],
        loginname: [
          {
            required: true,
            message: "请输入请输入登录账号",
            trigger: "blur"
          }
        ],
        loginpwd: [
          {
            required: true,
            validator: pwdCheck,
            trigger: "blur"
          }
        ],
        loginpwd1: [
          {
            required: true,
            validator: pwdAgainCheck,
            trigger: "blur"
          }
        ],
        enabled: [
          {
            required: true,
            type: "number",
            message: "请选择状态",
            trigger: "change"
          }
        ],
        regionid: [
          {
            required: true,
            type: "number",
            message: "请选择区域",
            trigger: "change"
          }
        ]
      },
      // 新建/编辑
      adminInfo: {
        show: false,
        timer: null,
        second: 60,
        adminid: null,
        aname: "",
        loginname: "",
        loginpwd: "",
        loginpwd1: "",
        phone: "",
        msgcode: "",
        enabled: 1,
        regionid: null,
        address: "",
        comm: ""
      },
      // 查看
      viewInfo: {
        show: false,
        enabled: "",
        aname: "",
        loginname: "",
        phone: "",
        regionName: "",
        address: "",
        comm: ""
      },
      columns: [
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        {
          title: "名称",
          key: "aname",
          align: "center"
        },
        {
          title: "登录账号",
          key: "loginname",
          align: "center"
        },
        {
          title: "手机号码",
          key: "phone",
          width: 135,
          align: "center"
        },
        {
          title: "状态",
          slot: "enabledSlot",
          width: 80,
          align: "center"
        },
        {
          title: "区域名称",
          key: "regionName",
          align: "center"
        },
        {
          title: "最后登录IP",
          key: "lastip",
          width: 150,
          align: "center"
        },
        {
          title: "最后登录时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 180,
          align: "center"
        }
      ]
    };
  },
  created() {
    this.getSearchRegionList();
    this.searchList();
  },
  methods: {
    // 获取搜索区域列表
    getSearchRegionList() {
      region_list_sel_pt({}).then((data) => {
        if (data.code === 0) {
          this.searchForm.dropList = data.obj;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 搜索
    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() {
      admin_list_pt({
        page: this.searchForm.page,
        size: this.searchForm.size,
        enabled: this.searchForm.enabled,
        aname: this.searchForm.aname,
        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,
        adminid: null,
        aname: "",
        loginname: "",
        loginpwd: generateRandomString(8),
        loginpwd1: "",
        phone: "",
        msgcode: "",
        enabled: 1,
        regionid: null,
        address: "",
        comm: ""
      };
    },
    // 获取短信验证码
    getMsgCode() {
      if (this.adminInfo.second < 60) {
        return;
      }
      // 手机号验证
      if (!this.adminInfo.phone) {
        this.$Message.error("手机号码不能为空");
        return;
      }
      let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!filter.test(this.adminInfo.phone)) {
        this.$Message.error("手机号码格式不正确");
        return;
      }
      this.setRegionSecond();
      login_msg_code({
        phone: this.adminInfo.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.adminid &&
            (this.adminInfo.loginpwd || this.adminInfo.loginpwd1)
          ) {
            const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,32}$/;
            if (!reg.test(this.adminInfo.loginpwd)) {
              this.$Message.error(
                "密码必须包含大小写字母和数字的组合，长度在8-32之间。"
              );
              return;
            }
            if (this.adminInfo.loginpwd != this.adminInfo.loginpwd1) {
              this.$Message.error("两次输入密码不一致！");
              return;
            }
          }
          let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          if (this.adminInfo.phone && !filter.test(this.adminInfo.phone)) {
            this.$Message.error("手机号码格式不正确");
            return;
          }
          if (this.adminInfo.phone && !this.adminInfo.msgcode) {
            this.$Message.error("请输入短信验证码");
            return;
          }
          if (this.adminInfo.timer) {
            clearInterval(this.adminInfo.timer);
            this.adminInfo.timer = null;
          }
          this.adminInfo.show = false;
          let api = this.adminInfo.adminid ? admin_edit : admin_add;
          let form = {
            aname: this.adminInfo.aname,
            loginname: this.adminInfo.loginname,
            loginpwd: this.adminInfo.loginpwd,
            phone: this.adminInfo.phone,
            msgcode: this.adminInfo.msgcode,
            enabled: this.adminInfo.enabled,
            regionid: this.adminInfo.regionid,
            address: this.adminInfo.address,
            comm: this.adminInfo.comm
          };
          if (this.adminInfo.adminid) {
            form.adminid = this.adminInfo.adminid;
          }
          api(form).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 查看
    toView(row) {
      this.viewInfo = {
        show: true,
        enabled: row.enabled,
        aname: row.aname,
        loginname: row.loginname,
        phone: row.phone,
        regionName: row.regionName,
        address: row.address,
        comm: row.comm
      };
    },
    // 编辑
    toEdit(row) {
      this.adminInfo = {
        show: true,
        timer: null,
        second: 60,
        adminid: row.adminid,
        aname: row.aname,
        loginname: row.loginname,
        loginpwd: row.loginpwd,
        loginpwd1: row.loginpwd1,
        phone: row.phone,
        msgcode: row.msgcode,
        enabled: row.enabled,
        regionid: row.regionid,
        address: row.address,
        comm: row.comm
      };
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          admin_delete({
            adminid: row.adminid,
            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 ? admin_enable : admin_disabled;
      api({
        adminid: row.adminid,
        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>
