<template>

  <el-form label-width="100px" :model="data" :rules="rules" ref="baseFormRef">
    <el-form-item label="手机号" prop="userName" required>
      <el-input disabled v-model="data.userName" style="width: 300px" :maxlength="500" placeholder="请输入" />
    </el-form-item>
    <el-form-item label="验证码" prop="msgAuthCode" required>
      <el-input v-model="data.msgAuthCode" style="width: 190px" :maxlength="500" placeholder="请输入" />
      <el-button type="danger" style="margin-left: 10px" @click="getMsgCode">获取验证码</el-button>
    </el-form-item>
    <el-form-item label="密码" prop="password" required>
      <el-input autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" v-model="data.password"
        :type="addPassFlag ? 'text' : 'password'" style="width: 300px" :maxlength="500"
        placeholder="请输入8-16位数字、字母大小写组合">
        <template #suffix>
          <span @click="addPassFlag = !addPassFlag" style="cursor: pointer;">
            <el-icon v-if="addPassFlag">
              <View />
            </el-icon>
            <el-icon v-else>
              <Hide />
            </el-icon>
          </span>
        </template>
      </el-input>

    </el-form-item>
    <el-form-item label="密码确认" prop="confirmPwd" required>
      <el-input autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" v-model="data.confirmPwd"
        :type="addPassFlag ? 'text' : 'password'" style="width: 300px" :maxlength="500"
        placeholder="请输入8-16位数字、字母大小写组合">
        <template #suffix>
          <span @click="addPassFlag = !addPassFlag" style="cursor: pointer;">
            <el-icon v-if="addPassFlag">
              <View />
            </el-icon>
            <el-icon v-else>
              <Hide />
            </el-icon>
          </span>
        </template>
      </el-input>

    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { QuiskExpose } from "@/helper/mount";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { View, Hide } from '@element-plus/icons-vue';
import type { OrganizationType } from '@/request/organization'
import {
  getOrgListFetch,
  getMsgAuthCode,
  UserType
} from "@/request";

import { ref, reactive, unref, onMounted, watchEffect } from "vue";
const addPassFlag = ref(false)//图标显示标识

const baseFormRef = ref<FormInstance>();

type SelectType = {
  value: string, id: number
}

const allOrgs = ref<SelectType[]>([]);


const rules = reactive<FormRules>({


  userName: [
    { required: true, message: "请输入账号", trigger: "blur" },
  ],
  msgAuthCode: [
    { required: true, message: "请输入验证码", trigger: "change" },
  ],

  password: [
    { required: true, pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/, message: "请输入8-16位数字、字母大小写组合", trigger: "blur" },
    { required: true, min: 8, message: '密码太短！', trigger: "blur" },
  ],
  confirmPwd: [
    { required: true, pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/, message: "请输入8-16位数字、字母大小写组合", trigger: "blur" },
    { required: true, min: 8, message: '密码太短！', trigger: "blur" },
  ]
},)

const props = defineProps<{
  user: UserType,
  submit: (data: UserType) => Promise<any>;
}>();
const data = ref<UserType>({
  nickName: "",
  orgId: undefined,
  password: "",
  msgAuthCode: "",
  confirmPwd: "",
  status: 0,
  userName: "",
  createBy: "",
  createTime: "",
  fdkkId: 0,
  head: "",
  orgName: "",
  tbStatus: 0,
  updateBy: "",
  updateTime: "",
  userId: 0,
  roleNames: ""
});
const isDisableMsg = ref(false)

onMounted(async () => {
  const data = await getOrgListFetch({
    pageNum: 1,
    pageSize: 10000,
  })
  // console.log('allOrgs', data.records);
  allOrgs.value = Array.from(data.records).map((item: OrganizationType) => {
    const i: SelectType = { value: item['orgName'], id: item['orgId'] }
    return i
  });

})

// const setParentId = () => {
//   if (user.value) {
//     const isSuper = user.value.roles.filter(item => item.roleKey === "super_admin").length > 0;
//     data.value.parentId = isSuper ? 0 : Number(user.value.orgId)
//   }
// }
watchEffect(() => {
  if (props.user) {
    data.value = { ...props.user }
  }
})

const getMsgCode = async () => {
  const res = await getMsgAuthCode('+86', "13750087092")
  console.log('res', res)
  let timer = null
  if (res.success) {
    timer && clearTimeout(timer)
    isDisableMsg.value = true
    timer = setTimeout(() => {
      isDisableMsg.value = false
    }, 60 * 1000)
  }

}

// const handleSelect = (orgId: number) => {
//   const item = Array.from(allOrgs.value).find(i => i.id === orgId)
//   if (item) {
//     data.value.orgName = item.value
//   }
// }
defineExpose<QuiskExpose>({
  async submit() {
    if (unref(baseFormRef)) {
      const res = await unref(baseFormRef)?.validate();
      if (res) {
        await props.submit(data.value as any as UserType);
        ElMessage.success('编辑成功！');
      }
    } else {
      throw "";
    }
  },
});
</script>