<!-- 
 * @Description: 表单
 * @Author: huguodong 
 * @Date: 2023-12-15 15:45:28
!-->
<template>
  <div>
    <form-container v-model="visible" title="人员选择" form-size="600px">
      <el-form
        ref="userFormRef"
        :rules="rules"
        :disabled="liveUserProps.disabled"
        :model="liveUserProps.record"
        :hide-required-asterisk="liveUserProps.disabled"
        label-width="auto"
        label-suffix=" :"
      >
        <s-form-item label="指定推送人" prop="userId">
          <el-button link type="primary" @click="showSelector">选择</el-button>
          <el-tag v-if="liveUserProps.record.userId" class="ml-3px" type="warning" closable @close="removeDirector">{{
            liveUserProps.record.userInfo?.name
          }}</el-tag>
        </s-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onClose"> 取消 </el-button>
        <el-button v-show="!liveUserProps.disabled" type="primary" @click="handleSubmit"> 确定 </el-button>
      </template>
    </form-container>
    <user-selector ref="userSelectorRef" :org-tree-api="sysOrgApi.tree" :user-selector-api="sysUserApi.selector" @successful="handleChooseUser" />
  </div>
</template>

<script setup lang="ts">
import { SysOrg, SysUser, sysOrgApi, sysPositionApi, sysRoleApi, sysUserApi, monitorLIVEApi } from "@/api";
import { FormOptEnum, SysDictEnum } from "@/enums";
import { required } from "@/utils/formRules";
import { FormInstance } from "element-plus";
import { useDictStore } from "@/stores/modules";
import { UserSelectorInstance } from "@/components/Selectors/UserSelector/interface";

const visible = ref(false); //是否显示表单
const dictStore = useDictStore(); //字典仓库

// 表单参数
const liveUserProps = reactive<FormProps.Base<any>>({
  opt: FormOptEnum.ADD,
  record: {},
  disabled: false
});

// 表单验证规则
const rules = reactive({
  userId: [required("请选择指定推送人")]
});

/**
 * 打开表单
 * @param props 表单参数
 */
function onOpen(props: FormProps.Base<any>) {
  Object.assign(liveUserProps, props); //合并参数
  if (props.opt == FormOptEnum.ADD) {
    //如果是新增,设置默认值
  }
  visible.value = true; //显示表单
  if (props.record.pushUserId) {
    //如果传了id，就去请求api获取record
    liveUserProps.record.userId = props.record.pushUserId;
    liveUserProps.record.userInfo = props.record.sysUserItem;
    // sysOrgApi.detail({ id: props.record.id }).then(res => {
    //   liveUserProps.record.userId = res.data;
    // });
  }
}

// 提交数据（新增/编辑）
const userFormRef = ref<FormInstance>();
/** 提交表单 */
async function handleSubmit() {
  userFormRef.value?.validate(async valid => {
    if (!valid) return; //表单验证失败
    let params: any = {
      warnCode: "",
      userId: ""
    };
    if (liveUserProps.opt == "预警推送人") {
      params.warnCode = liveUserProps.record.warnCode;
      params.userId = liveUserProps.record.userId;
      //提交表单
      await monitorLIVEApi
        .setWarningPushPerson(params)
        .then(() => {
          liveUserProps.successful!(); //调用父组件的successful方法
        })
        .finally(() => {
          onClose();
        });
    }
  });
}

/** 关闭表单*/
function onClose() {
  visible.value = false;
  liveUserProps.record.userId = null;
  liveUserProps.record.userInfo = null;
}

const userSelectorRef = ref<UserSelectorInstance>(); //用户选择器引用
/** 显示用户选择器 */
function showSelector() {
  //将liveUserProps.record.userInfo转为 SysUser.SysUserInfo[]类型
  const userInfo = liveUserProps.record.userInfo ? [liveUserProps.record.userInfo] : [];
  userSelectorRef.value?.showSelector(userInfo);
}

/** 选择用户 */
function handleChooseUser(data: SysUser.SysUserInfo[]) {
  // 选择用户后，将用户id赋值给liveUserProps.record.userId
  if (data.length > 0) {
    liveUserProps.record.userId = data[0].id;
    liveUserProps.record.userInfo = data[0];
  }
}

/** 移除主管 */
function removeDirector() {
  liveUserProps.record.userId = null;
  liveUserProps.record.userInfo = null;
}
// 暴露给父组件的方法
defineExpose({
  onOpen
});
</script>

<style lang="scss" scoped></style>
