<template>
  <el-form ref="ruleFormRef" label-position="top" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
    <el-form-item label="已选择手铐">
      <div>{{ deviceNames }}</div>
    </el-form-item>
    <el-form-item label="辖区" prop="org">
      <el-select v-model="ruleForm.org" placeholder="请选择辖区" @change="getAccountListOrg">
        <el-option v-for="item in orgAllData" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="人员" prop="accountId">
      <el-select v-model="ruleForm.accountId" placeholder="请选择人员">
        <el-option v-for="item in accountLis" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>

    <el-form-item class="footr">
      <el-button type="primary" @click="submitForm(ruleFormRef)"> 保存 </el-button>
      <el-button @click="emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, onMounted, PropType, reactive, ref, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { TDevice, TOrg } from "@/api/index.d";
import { accountListOrg } from "@/api/index";
interface IForm {
  devices: number[];
  org: number | string;
  accountId: number | string;
}

const ruleFormRef = ref<FormInstance>();
const accountLis = ref([]);

const props = defineProps({
  orgAllData: {
    type: Array as PropType<TOrg.IOrgRecordRes[]>,
    dfault: () => {},
  },
  selectDeviceList: {
    type: Array as PropType<TDevice.IListRes[]>,
    dfault: () => {},
  },
  api: {
    type: Function,
  },
});
const emit = defineEmits(["close"]);

const getAccountListOrg = (orgId: number, accountId?: number) => {
  accountLis.value = [];
  ruleForm.accountId = "";
  accountListOrg(orgId).then((res) => {
    accountLis.value = res;
    if (accountId) {
      ruleForm.accountId = accountId;
    }
  });
};
const deviceNames = computed(() => props.selectDeviceList.map((item) => item.deviceId).join("、"));

const ruleForm = reactive<IForm>({
  devices: props.selectDeviceList.map((item) => item.deviceId),
  org: "",
  accountId: "",
});

onMounted(() => {
  if (props.selectDeviceList.length == 1) {
    let item = props.selectDeviceList[0];
    ruleForm.org = item.orgId;
    getAccountListOrg(item.orgId, item.accountId);
  }
});

const rules = reactive<FormRules<typeof ruleForm>>({
  org: [{ required: true, message: "请选择辖区", trigger: "blur" }],
  accountId: [{ required: true, message: "请选择人员", trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      props.api(ruleForm);
    }
  });
};
</script>
<style scoped lang="less">
.footr {
  margin-top: 20px;
}
.footr :deep(.el-form-item__content) {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  margin-top: 20px;
}
</style>
