<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="NuBaseInfoForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="区域名称" v-bind="validateInfos.nuName" id="NuBaseInfoForm-nuName" name="nuName">
                <a-input v-model:value="formData.nuName" placeholder="区域名称自动生成" allow-clear
                  :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="区域编码" v-bind="validateInfos.nuId" id="NuBaseInfoForm-nuId" name="nuId">
                <a-input v-model:value="formData.nuId" placeholder="编码自动生成" allow-clear
                  :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="区域属性" v-bind="validateInfos.areaFlag" id="NuBaseInfoForm-areaFlag" name="areaFlag">
                <j-dict-select-tag v-model:value="formData.areaFlag" dictCode="nu_type" placeholder="请选择区域属性"
                  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="摄像头" v-bind="validateInfos.iotSn" id="NuBaseInfoForm-iotSn" name="iotSn">
                <a-input-search v-model:value="formData.iotSn" placeholder="请选择摄像头" enter-button="选择" readonly @search="chercSxt" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <CheckSxtModal ref="checkSxtModal" @success="handleSxtSuccess"/>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { getValueType } from '/@/utils';
import { addNuIot } from '../DeviceSync.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import CheckSxtModal from '/@/views/deviceSync/compoents/CheckSxtModal.vue'

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
});
const formRef = ref();
const checkSxtModal = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  nuName: '',
  nuId: '',
  orgCode: '',
  areaFlag: '',
  status: '',
  iotSn:'',
});
const orgInfo = ref<any>({})
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  areaFlag : [{ required: true, message: '请选择区域属性!'},],
  // iot : [{ required: true, message: '请选择摄像头!'},],
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});
//选择摄像头
function chercSxt(){
  checkSxtModal.value.disabled = true;
  checkSxtModal.value.init({})

}
//选择摄像头成功
function handleSxtSuccess(record) {
console.log("🚀 ~ handleSxtSuccess ~ record:", record)
  formData.iotSn = record.sn;
}

/**
 * 新增
 */
function add(record) {
  console.log("🚀 ~ add ~ record:", record)
  orgInfo.value = record;
  edit(record);
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}
//选择摄像头
function onSearch() {
  console.log('orgInfo', orgInfo.value);
  formData.iot = '111';
}

/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  if (!model.id) {
    model.status = "0";
  }
  // if(!model.iotSn){
  //   createMessage.warning("请选择摄像头！");
  //     confirmLoading.value = false;
  // return;
  // }
  await addNuIot(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success("添加成功！");
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
