<template>
  <div>
    <el-drawer v-model="isDrawer" :size="350" :title="title" @close="closeDrawer">
      <el-form :model="formParams" :rules="rules" ref="formRef" label-position="left" :label-width="85">
        <el-form-item label="设备名称：" prop="name">
          <el-input v-model="formParams.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号：" prop="code" :error="codeError">
          <el-input v-model="formParams.code" placeholder="自定义编码，不可重复" />
        </el-form-item>
        <el-form-item label="设备品牌：" prop="nvrType">
          <el-select v-model="formParams.nvrType" placeholder="请选择设备品牌">
            <el-option v-for="item in brands" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="IP地址：" prop="nvrIp" :error="ipError">
          <el-input v-model="formParams.nvrIp" placeholder="请输入设备IP地址，不可重复" />
        </el-form-item>
        <el-form-item label="端口：" prop="nvrPort">
          <el-input v-model="formParams.nvrPort" placeholder="请输入设备端口" />
        </el-form-item>
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="formParams.username" placeholder="请输入设备用户名" />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="formParams.password" placeholder="请输入设备密码" type="password" show-password />
        </el-form-item>
        <!-- <el-form-item label="使用场景：" prop="workshopList">
          <el-tree-select class="temp" v-model="workLocations" :data="locationOptions" multiple
            :render-after-expand="false" placeholder="请选择使用该NVR的车间" @change="handleCascaderChange" />
        </el-form-item> -->
        <el-form-item label="负责人：" prop="principal">
          <el-input v-model="formParams.principal" placeholder="请输入设备安装负责人" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="formParams.remark" type="textarea" maxlength="200" :autosize="{ minRows: 3 }"
            show-word-limit placeholder="请输入该设备相关备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="btn-box">
          <el-button @click="closeDrawer">取消</el-button>
          <el-button type="primary" @click="formSubmit">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { brands, useWorkLocation } from '../constant';
import { FormRules } from 'element-plus';
import {
  NVRListItem,
  NVRListItemAll,
  addNVRListItem,
  updateNVRListItem,
} from '@/api/camera/camera-nvr';

interface Props {
  title: String;
}
const props = defineProps<Props>();
const emit = defineEmits(['form-submit', 'form-edit']);

const isDrawer = ref(false);
const formRef: any = ref(null);
// const ismultiple = { multiple: true };

const { getLocationOptions } = useWorkLocation();
// const workLocations = ref<[number | undefined, number | undefined] | []>([]);
const workLocations = ref<number[]>([]);

const codeError = ref('');
const ipError = ref('');

const initFormNvr = () => ({
  name: '',
  code: '',
  nvrIp: '',
  nvrType: '',
  nvrPort: '',
  username: '',
  password: '',
  principal: '',
  remark: '',
});
const formParams = ref<NVRListItem>(initFormNvr());

const deleteKey = (obj, ...args) => {
  args.forEach((v) => {
    delete obj[v];
  });
  return obj;
};
const openDrawer = (row: NVRListItemAll) => {
  isDrawer.value = true;
  if (row) {
    formParams.value = Object.assign(formParams.value, row);
    deleteKey(
      formParams.value,
      'createdAt',
      'isDeleted',
      'tenantId',
      'updatedAt',
      'workshopName',
    );
    return;
  }
};

const closeDrawer = () => {
  isDrawer.value = false;
  formRef.value.resetFields();
  formParams.value = Object.assign(formParams.value, initFormNvr());
  workLocations.value = [];
};

const isAddUser = computed(() => {
  return props.title === '添加NVR';
});

const rules: FormRules = {
  name: { required: true, message: '设备名称不能为空', trigger: 'blur' },
  code: [
    { required: true, message: '设备编号不能为空', trigger: 'change' },
    {
      pattern: /^[a-zA-Z0-9-_]+$/,
      message: '请输入大小写字母、数字、-、_的组合',
      trigger: 'change',
    },
  ],
  nvrType: { required: true, message: '设备品牌不能为空', trigger: 'change' },
  nvrIp: { required: true, message: '设备IP不能为空', trigger: 'change' },
  nvrPort: { required: true, message: '端口不能为空', trigger: 'blur' },
  username: { required: true, message: '用户名不能为空', trigger: 'blur' },
  password: { required: true, message: '密码不能为空', trigger: 'blur' },
  workshopList: { required: true, message: '使用场景不能为空', trigger: 'change' },
};

const formSubmit = () => {
  const errorText = ref('');
  // 捕获当前表单中是否有el-form-item__error即错误信息
  const errorTipElements = document.querySelectorAll('.el-form-item__error');
  errorTipElements.forEach((element) => {
    if (element.textContent) errorText.value = element.textContent;
  });

  if (errorText.value === '') {
    // codeError.value = '';
    // ipError.value = '';
    formRef.value.validate((valid) => {
      if (valid) {
        const nvrData = {
          name: formParams.value.name,
          code: formParams.value.code,
          nvrIp: formParams.value.nvrIp,
          nvrType: formParams.value.nvrType,
          nvrPort: formParams.value.nvrPort,
          username: formParams.value.username,
          password: formParams.value.password,
          principal: formParams.value.principal,
          remark: formParams.value.remark,
        };

        if (isAddUser.value) {
          addNVRListItem(nvrData).then(() => {
            emit('form-submit');
            closeDrawer();
            // if (Object.getOwnPropertyNames(res).length != 0) {
            //   codeError.value = res.code;
            //   ipError.value = res.nvrIp;
            // } else {
            // }
          });
        } else {
          updateNVRListItem(formParams.value).then(() => {
            emit('form-edit');
            closeDrawer();
            // if (Object.getOwnPropertyNames(res).length != 0) {
            //   codeError.value = res.code;
            //   ipError.value = res.nvrIp;
            // } else {
            // }
          });
        }
      }
    });
  }
};

defineExpose({
  openDrawer,
  closeDrawer,
});

onMounted(() => {
  getLocationOptions();
});
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  position: relative;

  > :first-child {
    margin-left: 32px;
    font-weight: 600;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.88);
  }

  .el-drawer__close-btn {
    position: absolute;
    color: #000;
  }
}

:deep(.el-drawer__body) {
  border-top: 1px solid #0000000f;
}

:deep(.el-form-item__label) {
  padding-right: 0;
}

:deep(.el-cascader) {
  width: 230px;
}

.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-top: 10px;
}

:deep(.temp .el-select__selection) {
  min-height: 24px;
  max-height: 55px;
  overflow: auto;
}
</style>
