<template>
  <div class="registe-container">
    <div class="bg-breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/login' }"> 登录 </el-breadcrumb-item>
        <el-breadcrumb-item> 注册 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="registe-content">
      <div class="registe-header">
        <div>业务系统注册</div>
        <div class="registe-heade-sub">注册信息提示审批后即可登录</div>
      </div>
      <div class="registe-form">
        <el-form ref="infoFormRef" :model="infoForm" label-width="120px" :rules="infoFormRules" style="width: 90%">
          <div class="registe-info">
            <div class="title">
              <div><span class="icon_box"></span> 基础信息</div>
              <div class="dashed_line"></div>
            </div>
            <div class="info-form">
              <el-form-item prop="organization_id" label="所属机构">
                <el-tree-select
                  v-model="infoForm.organization_id"
                  :data="orgData"
                  :props="treeProps"
                  :render-after-expand="false"
                  filterable
                  style="width: 100%" />
              </el-form-item>
              <el-form-item prop="business_name" label="业务系统名称">
                <el-input v-model="infoForm.business_name" placeholder="请输入" maxlength="20" show-word-limit />
              </el-form-item>
              <el-form-item prop="develop_id" label="开发厂商名称">
                <el-select v-model="infoForm.develop_id" placeholder="请选择，如需新增，请输入任意字符" filterable style="width: 100%">
                  <el-option
                    v-for="item in developList"
                    :key="'develop_' + item.dict_id"
                    :label="item.dict_name"
                    :value="item.dict_id" />
                  <template #empty>
                    <div class="select-empty">
                      <div>无匹配数据</div>
                      <el-button style="height: 32px; margin-top: 10px" @click="addDevelop"> 新增</el-button>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item prop="system_account" label="账号">
                <el-input v-model="infoForm.system_account" placeholder="请输入" />
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input type="password" v-model="infoForm.password" placeholder="请输入" />
              </el-form-item>
              <el-form-item prop="confirm_password" label="确认密码">
                <el-input type="password" v-model="infoForm.confirm_password" placeholder="请输入" />
              </el-form-item>
              <el-form-item prop="phone" label="手机号">
                <el-input v-model="infoForm.phone" placeholder="请输入" />
              </el-form-item>
              <el-form-item prop="code" label="验证码">
                <div class="msg-code">
                  <el-input v-model="infoForm.code" placeholder="请输入" style="860px"> </el-input>
                  <div class="yzm_img">
                    <el-button
                      type="primary"
                      style="width: 100%; height: 34px"
                      @click="sendSms"
                      :disabled="countDown > 0">
                      {{ countDown > 0 ? countDown + "秒后再次获取" : "发送验证码" }}
                    </el-button>
                  </div>
                </div>
              </el-form-item>
              <el-form-item prop="business_desc" label="业务系统概述">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="infoForm.business_desc"
                  placeholder="请输入"
                  maxlength="200"
                  show-word-limit />
              </el-form-item>
            </div>
          </div>
          <div class="registe-info">
            <div class="title">
              <div><span class="icon_box"></span> 联系人信息</div>
              <div class="dashed_line"></div>
            </div>
            <div class="info-form">
              <el-form-item prop="contact_name" label="联系人">
                <el-input v-model="infoForm.contact_name" placeholder="请输入" />
              </el-form-item>
              <el-form-item prop="contact_phone" label="联系电话">
                <el-input v-model="infoForm.contact_phone" placeholder="请输入" />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
      <div class="registe-footer">
        <el-button @click="router.go(-1)">返回登录页</el-button>
        <el-button type="primary" @click="submit">注册</el-button>
      </div>
    </div>
    <el-dialog v-model="dialogVisit" title="新增" width="520px" :before-close="handleCloseDialog" destroy-on-close>
      <div class="dialog_form">
        <el-form
          ref="developFormRef"
          :model="developForm"
          label-width="120px"
          :rules="developFormRules"
          style="width: 90%">
          <el-form-item prop="develop" label="开发厂商名称">
            <el-input v-model="developForm.develop" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import axios from "@/request/http.js";
import { Encrypt } from "@/services/secret.js";
import { ElMessage } from "element-plus";
import { validatePhone } from "@/services/rules.js";

const validateBusinessName = (rule, value, callback) => {
  let reg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
  if (!reg.test(value)) {
    callback(new Error("只能输入字母、数字和汉字"));
  } else {
    let params = { business_name: value };

    axios.post(`/apaas/system/v5/user/checkBusiness`, params).then((res) => {
      if (res.data.code == 200) {
        callback();
      } else {
        callback(new Error(res.data.data));
      }
    });
  }
};

const validateSystemAccount = (rule, value, callback) => {
  let reg = /^[a-zA-Z0-9]+$/;
  if (!reg.test(value)) {
    callback(new Error("只能输入字母和数字"));
  } else {
    let params = { system_account: value };

    axios.post(`/apaas/system/v5/user/checkAccount`, params).then((res) => {
      if (res.data.code == 200) {
        callback();
      } else {
        callback(new Error(res.data.data));
      }
    });
  }
};

const checkPhoneRepet = (rule, value, callback) => {
  let params = { phone: value };
  axios.post(`/apaas/system/v5/user/checkPhone`, params).then((res) => {
    if (res.data.code == 200) {
      callback();
    } else {
      callback(new Error(res.data.data));
    }
  });
};

const validatePass = (rule, value, callback) => {
  if (value !== state.infoForm.password) {
    callback(new Error("密码输入不一致"));
  } else {
    callback();
  }
};

const router = useRouter();
const state = reactive({
  infoForm: {
    organization_id: "",
    business_name: "",
    develop_id: "",
    system_account: "",
    password: "",
    confirm_password: "",
    phone: "",
    code: "",
    business_desc: "",
    contact_name: "",
    contact_phone: "",
  },
  infoFormRules: {
    organization_id: [{ required: true, message: "请选择开发厂商", trigger: "blur" }],
    business_name: [
      { required: true, message: "请输入业务系统名称", trigger: "blur" },
      { validator: validateBusinessName, trigger: "blur" },
    ],
    develop_id: [{ required: true, message: "请选择开发厂商", trigger: "blur" }],
    system_account: [
      { required: true, message: "请输入账号", trigger: "blur" },
      { min: 4, message: "帐号长度不得低于4个字符", trigger: "blur" },
      { max: 20, message: "帐号最大长度为20个字符", trigger: "blur" },
      { validator: validateSystemAccount, trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 8, message: "密码长度不得低于8位", trigger: "blur" },
    ],
    confirm_password: [
      { required: true, message: "请确认密码", trigger: "blur" },
      { validator: validatePass, trigger: "blur" },
    ],
    phone: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { validator: validatePhone, trigger: "blur" },
      { validator: checkPhoneRepet, trigger: "blur" },
    ],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
    contact_name: [{ required: true, message: "请输入联系人", trigger: "blur" }],
    contact_phone: [
      { required: true, message: "请输入联系电话", trigger: "blur" },
      { validator: validatePhone, trigger: "blur" },
    ],
  },
  developForm: {
    develop: "",
  },
  developFormRules: {
    develop: [{ required: true, message: "请输入开发厂商名称", trigger: "blur" }],
  },
  dialogVisit: false,
  countDown: 0,
  countDownTimer: null,
  orgData: [],
  developList: [],
});
const treeProps = {
  label: "name",
  children: "Child",
  value: "organization_id",
};
// const loading = ref(false)
const list = ref([]);
const infoFormRef = ref(null);
const developFormRef = ref(null);

// const remoteMethod = (query) => {
//   if (query) {
//     loading.value = true
//     setTimeout(() => {
//       loading.value = false
//       state.devOptions = state.developList.filter((item) => {
//         return item.dict_name.includes(query)
//       })
//     }, 200)
//   } else {
//     state.devOptions = []
//   }
// }

const submit = () => {
  infoFormRef.value.validate((valid) => {
    if (valid) {
      const params = {
        organization_id: state.infoForm.organization_id,
        business_name: state.infoForm.business_name,
        business_desc: state.infoForm.business_desc,
        system_account: state.infoForm.system_account,
        password: Encrypt(state.infoForm.password),
        develop_id: state.infoForm.develop_id.toString(),
        contact_name: state.infoForm.contact_name,
        contact_phone: state.infoForm.contact_phone,
        phone: state.infoForm.phone,
        code: state.infoForm.code,
      };
      axios.post("/apaas/system/v5/user/register", params).then(({ data }) => {
        if (data.code == 200) {
          ElMessage.success("注册信息已提交！");
          router.go(-1);
        } else {
          ElMessage.error(data.data);
        }
      });
    }
  });
};

const sendSms = () => {
  infoFormRef.value.validateField("phone", (valid) => {
    if (valid) {
      axios.post("/apaas/system/v5/sms/verifyCode", { phone: state.infoForm.phone }).then(({ data }) => {
        if (data.code == 200) {
          countDownAction();
        }
      });
    }
  });
};

const countDownAction = () => {
  state.countDown = 60;
  if (state.countDownTimer) {
    clearInterval(state.countDownTimer);
  }

  state.countDownTimer = setInterval(() => {
    if (state.countDown > 0) {
      state.countDown--;
    } else {
      clearInterval(state.countDownTimer);
    }
  }, 1000);
};

const addDevelop = () => {
  state.dialogVisit = true;
};

const handleCloseDialog = () => {
  state.dialogVisit = false;
};

const confirmAdd = () => {
  developFormRef.value.validate((valid) => {
    if (valid) {
      axios
        .post("/apaas/system/v5/user/dict/develop/add", { dict_name: state.developForm.develop })
        .then(({ data }) => {
          if (data.code == 200) {
            state.infoForm.develop_id = data.data;
            getDevelopList();
          } else {
            ElMessage.error(data.data);
          }
          handleCloseDialog();
        });
    }
  });
};

const getOrgData = () => {
  axios.get("/apaas/system/v5/user/org/tree").then(({ data }) => {
    if (data.code == 200) {
      state.orgData = data.data || [];
    }
  });
};

const getDevelopList = () => {
  axios.get("/apaas/system/v5/user/dict/develop").then(({ data }) => {
    if (data.code == 200) {
      state.developList = data.data || [];
    }
  });
};

onMounted(() => {
  getOrgData();
  getDevelopList();
});

const {
  infoForm,
  infoFormRules,
  dialogVisit,
  developForm,
  developFormRules,
  countDown,
  countDownTimer,
  orgData,
  developList,
} = toRefs(state);
</script>

<style lang="scss" scoped>
.registe-container {
  margin: 0 auto;
  width: 1200px;

  height: 100%;
  .registe-content {
    background-color: #ffffff;
    box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    // height: calc(100% - 100px);
    .registe-header {
      padding: 20px 0;
      text-align: center;
      font-size: 22px;
      color: #1a1a1a;
      font-weight: bold;
      .registe-heade-sub {
        font-size: 14px;
        font-weight: 400;
        color: #404a62;
        padding: 10px 0;
      }
    }
    .registe-form {
      padding: 0 24px;
      .title {
        font-size: 18px;
        color: #1a1a1a;
        font-weight: 600;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        .icon_box {
          display: inline-block;
          width: 4px;
          height: 14px;
          background-color: #3759be;
          border-radius: 2px;
          margin-right: 5px;
        }
        .dashed_line {
          flex: 1;
          height: 1px;
          margin: 0 10px;
          border-bottom: dashed 1px #dadee7;
        }
      }
      .msg-code {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        .yzm_img {
          flex: 1;
          margin-left: 20px;
        }
      }
    }
    .registe-footer {
      border-top: solid 1px #e6e9ef;
      text-align: right;
      padding: 24px;
    }
  }
  .dialog_form {
    margin: 20px 0;
  }
}
</style>
