<template>
  <div class="system-edit-dic-container">
    <!-- 编辑产品/新增产品 -->
    <el-dialog :title="ruleForm.id !== 0 ? $t('message.device.dialogI18n.editPro') : $t('message.device.dialogI18n.addPro')" v-model="isShowDialog" width="769px">
      <el-form :model="ruleForm" ref="formRef" :rules="rules"  :label-width="currentLocale == 'en' ? '150px' : '120px'">
        <!-- 产品标识 -->
        <el-form-item :label="$t('message.device.formI18nLabel.productKey')" prop="key">
          <!-- 请输入产品标识 -->
          <el-input v-model="ruleForm.key" :placeholder="$t('message.device.formI18nPlaceholder.productKey')" :disabled="ruleForm.id" />
        </el-form-item>
        <!-- 产品名称 -->
        <el-form-item :label="$t('message.device.formI18nLabel.productName')" prop="name">
          <!-- 请输入产品名称 -->
          <el-input v-model="ruleForm.name" :placeholder="$t('message.device.formI18nPlaceholder.productName')" />
        </el-form-item>
        <!-- 产品图片 -->
        <el-form-item :label="$t('message.device.formI18nLabel.productImage')" prop="imageUrl">
          <uploadVue :img="imageUrl" @set-img="handleAvatarSuccess"></uploadVue>
        </el-form-item>
        <!-- 产品分类 -->
        <el-form-item :label="$t('message.device.formI18nLabel.productCategory')" prop="categoryId">
          <!-- 请选择分类 -->
          <el-cascader :options="cateData" :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }" :placeholder="$t('message.device.formI18nPlaceholder.productCategory')" clearable v-model="ruleForm.categoryId">
            <template #default="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>

          <!-- 添加产品分类 -->
          <el-button type="success" @click="onOpenAddCategory()" style="margin-left: 5px">{{ $t('message.device.tableI18nAction.addProductCategory') }}</el-button>
        </el-form-item>
        <!-- 消息协议 -->
        <el-form-item :label="$t('message.device.formI18nLabel.messageProtocol')" prop="messageProtocol">
          <!-- 请选择消息协议 -->
          <el-select v-model="ruleForm.messageProtocol" :placeholder="$t('message.device.formI18nPlaceholder.messageProtocol')">
            <el-option v-for="dict in messageData" :key="dict.types" :label="dict.title" :value="dict.name"> </el-option>
            <!-- 增加系统默认的mqtt选项 -->
            <el-option label="Sagoo Mqtt" value="SagooMqtt"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 接入方式 -->
        <el-form-item :label="$t('message.device.formI18nLabel.transportProtocol')" prop="transportProtocol">
          <!-- 请选择接入方式 -->
          <el-select v-model="ruleForm.transportProtocol" :placeholder="$t('message.device.formI18nPlaceholder.transportProtocol')" @change="transportProtocolChange">
            <el-option v-for="dict in network_server_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 
          1，mqtt协议设备的认证
            在添加设备的页面，增加MQTT服务协议设备的认证方式的处理。
            当传输协议选择为：MQTT服务的时候，下面出现 认证方式的下拉列，分别为Basic、AccessToken接入两个下拉选项。
            Basic方式：
            选择这个方式的时候：页面出现，用户名及密码输入框。
            AccessToken接入方式：
            选择这个方式的时候：页面出现 Aceess Token的输入框
          2，TCP及其它协议认证
          这些配合【网络组件】功能中涉及到的设备通讯协议认证的处理。如果涉及到证书的，需要调用【证书管理】功能维护的证书列表。 
        -->
        <!-- 
          设备认证、网络组件服务增加认证方式authType（1=Basic，2=AccessToken，3=证书）
          涉及接口：产品添加、编辑、扩展信息更新；设备添加、编辑；网络组件服务添加、编辑 
        -->
        <!-- 设备认证 -->
        <template v-if="ruleForm.authType === 1 || ruleForm.authType === 2">
          <!-- 认证方式 -->
          <el-form-item :label="$t('message.device.formI18nLabel.authType')" prop="">
            <el-radio-group v-model="ruleForm.authType">
              <el-radio :label="1">Basic</el-radio>
              <el-radio :label="2">AccessToken</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="ruleForm.authType === 1">
            <!-- 用户名 -->
            <el-form-item :label="$t('message.device.formI18nLabel.authUser')" prop="authUser">
              <el-input v-model="ruleForm.authUser" :placeholder="$t('message.device.formI18nPlaceholder.authUser')" />
            </el-form-item>
            <!-- 密码 -->
            <el-form-item :label="$t('message.device.formI18nLabel.authPasswd')" prop="authPasswd">
              <el-input type="password" v-model="ruleForm.authPasswd" :placeholder="$t('message.device.formI18nPlaceholder.authPasswd')" />
            </el-form-item>
          </template>
          <template v-else>
            <!-- Aceess Token -->
            <el-form-item :label="$t('message.device.formI18nLabel.accessToken')" prop="accessToken">
              <!-- 请输入Aceess Token -->
              <el-input v-model="ruleForm.accessToken" :placeholder="$t('message.device.formI18nPlaceholder.accessToken')" />
            </el-form-item>
          </template>
        </template>
        <template v-else-if="ruleForm.authType === 3">
          <!-- 认证证书 -->
          <el-form-item :label="$t('message.device.formI18nLabel.certificateId')" prop="certificateId">
            <!-- 请选择证书 -->
            <el-select v-model="ruleForm.certificateId" :placeholder="$t('message.device.formI18nPlaceholder.certificateId')">
              <el-option v-for="cert in certList" :key="cert.id" :label="cert.name" :value="cert.id"> </el-option>
            </el-select>
          </el-form-item>
        </template>
        <!-- 设备类型 -->
        <el-form-item :label="$t('message.device.formI18nLabel.deviceType')" prop="deviceType">
          <el-radio-group v-model="ruleForm.deviceType">
            <!-- 设备 -->
            <el-radio label="设备">{{ $t('message.device.formI18nOption.device') }}</el-radio>
            <!-- 网关 -->
            <el-radio label="网关">{{ $t('message.device.formI18nOption.gateway') }}</el-radio>
            <!-- <el-radio label="设备">直连设备</el-radio>
            <el-radio label="网关">网关设备</el-radio> -->
            <!-- 子设备 -->
            <el-radio label="子设备">{{ $t('message.device.formI18nOption.subDevice') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 产品描述 -->
        <el-form-item :label="$t('message.device.formI18nLabel.desc')" prop="desc">
          <!-- 请输入产品描述 -->
          <el-input v-model="ruleForm.desc" type="textarea" :placeholder="$t('message.device.formI18nPlaceholder.desc')"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <!-- 取 消 -->
          <el-button @click="onCancel">{{ $t('message.tableI18nAction.cancel') }}</el-button>
          <!-- 编辑 / 添加 -->
          <el-button type="primary" @click="onSubmit" :loading="submitLoading">{{ ruleForm.id ? $t('message.tableI18nAction.edit') : $t('message.tableI18nAction.add') }}</el-button>
        </span>
      </template>
    </el-dialog>
    <EditCategory ref="editCategoryRef" @getCateList="getCategoryList" />
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent, ref, unref, getCurrentInstance, computed } from "vue";
import api from "/@/api/device";
import certApi from "/@/api/certificateManagement";
import uploadVue from "/@/components/upload/index.vue";
import { validateNoSpace } from "/@/utils/validator";

import { ElMessage, UploadProps } from "element-plus";
import getOrigin from "/@/utils/origin";
import EditCategory from "/@/views/iot/device/category/component/addOrEdit.vue";
import { useI18n } from 'vue-i18n';


interface RuleFormState {
  id: number;
  categoryId: number | string;
  messageProtocol: string;
  transportProtocol: string;
  deviceType: string;
  name: string;
  key: string;
  authType: number | null;
  status: number;
  desc: string;
  icon: string;
  authUser: string;
  authPasswd: string;
  accessToken: string;
  certificateId: string;
}
interface DicState {
  isShowDialog: boolean;
  ruleForm: RuleFormState;
  cateData: any[];
  deptData: any[];
  messageData: any[];
  network_protocols: any[];
  tranData: any[];
  imageUrl: string;
  singleImg: string;
}

const form = {
  id: 0,
  name: "",
  key: "",
  categoryId: "",
  messageProtocol: "",
  transportProtocol: "",
  deviceType: "设备",
  status: 1,
  desc: "",
  icon: "",
  authType: null,
  authUser: "",
  authPasswd: "",
  accessToken: "",
  certificateId: "",
};

export default defineComponent({
  name: "deviceEditPro",
  components: { EditCategory, uploadVue },
  setup(prop, { emit }) {
    const formRef = ref<HTMLElement | null>(null);
    const baseURL: string | undefined | boolean = getOrigin();

    const { proxy } = getCurrentInstance() as any;
    const { network_server_type } = proxy.useDict("network_server_type");

    const certList = ref<any[]>([]);
    const submitLoading = ref(false);
    const editCategoryRef = ref();
    const { locale, t } = useI18n();
    const currentLocale = computed(() => locale.value);	
    const rules = computed(() => ({
        name: [
          // 产品名称不能为空
          { required: true, message: t("message.device.rules.productName"), trigger: "change" },
          // 产品名称不能超过32个字符
          { max: 32, message: t("message.device.rules.productNameMax32"), trigger: "change" },
          // 产品名称不能包含空格
          { validator: validateNoSpace, message: t("message.device.rules.productNameValidator"), trigger: "change" },
        ],
        key: [
          // 产品标识不能为空
          { required: true, message: t("message.device.rules.productKey"), trigger: "change" },
          // 产品标识不能包含空格
          { validator: validateNoSpace, message: t("message.device.rules.productKeyValidator"), trigger: "change" },
        ],
        // 消息协议不能为空
        messageProtocol: [{ required: true, message: t("message.device.rules.messageProtocol"), trigger: "change" }],
        // 接入方式不能为空
        transportProtocol: [{ required: true, message: t("message.device.rules.transportProtocol"), trigger: "change" }],
        // 产品分类不能为空
        categoryId: [{ required: true, message: t("message.device.rules.categoryId"), trigger: "change" }],
        // 设备类型不能为空
        deviceType: [{ required: true, message: t("message.device.rules.deviceType"), trigger: "change" }],
      }))

    const state = reactive<DicState>({
      isShowDialog: false,
      cateData: [], // 分类数据
      deptData: [], //
      messageData: [], //
      network_protocols: [], // 消息协议
      tranData: [], //
      imageUrl: "", //
      singleImg: baseURL + "/product/icon/upload",
      ruleForm: {
        ...form,
      }
    });

    const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
      state.imageUrl = response;
      state.ruleForm.icon = response;
    };

    // 打开弹窗
    const openDialog = (row?: any) => {
      resetForm();
      api.category.getList({ status: 1 }).then((res: any) => {
        state.cateData = res.category || [];
      });
      api.dept.getList({ status: -1 }).then((res: any) => {
        state.deptData = res || [];
      });
      api.product.getTypesAll({ types: "protocol" }).then((res: any) => {
        state.messageData = res || [];
      });

      // 证书列表
      certApi.certificateManagement.getAll().then((res: any) => {
        certList.value = res.Info || [];
      });
      // api.product.trunsport_protocol_list({ status: -1 }).then((res: any) => {
      //   state.tranData = res.data || [];
      // });
      if (row) {
        // api.dict.getType(row.dictId).then((res:any)=>{
        //   state.ruleForm = res.data.dictType
        // }
        state.imageUrl = row.icon;

        state.ruleForm = row;
        if (row.authType === 0) {
          transportProtocolChange(row.transportProtocol);
        }
      } else {
        state.imageUrl = "";
      }
      state.isShowDialog = true;
    };
    const resetForm = () => {
      state.ruleForm = {
        ...form,
      };
      const formWrap = unref(formRef) as any;
      if (formWrap) {
        formWrap.resetFields();
      }
    };
    // 关闭弹窗
    const closeDialog = () => {
      resetForm();

      state.isShowDialog = false;
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    const transportProtocolChange = (type: string) => {
      if (type === "mqtt_server") {
        state.ruleForm.authType = 1;
      } else {
        state.ruleForm.authType = 3;
      }
    };
    // 新增
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
          submitLoading.value = true;
          if (state.ruleForm.id !== 0) {
            //修改
            api.product
              .edit(state.ruleForm)
              .then(() => {
                ElMessage.success(t("message.tableI18nConfirm.editSuccess"));
                closeDialog(); // 关闭弹窗
                emit("typeList");
              })
              .finally(() => (submitLoading.value = false));
          } else {
            //添加
            api.product
              .add(state.ruleForm)
              .then(() => {
                ElMessage.success(t("message.tableI18nConfirm.addSuccess"));
                closeDialog(); // 关闭弹窗
                emit("typeList");
              })
              .finally(() => (submitLoading.value = false));
          }
        }
      });
    };
    // 打开新增产品分类弹窗
    const onOpenAddCategory = () => {
      editCategoryRef.value.openDialog();
    };
    // 获取产品分类列表
    const getCategoryList = () => {
      api.category.getList({ status: 1 }).then((res: any) => {
        state.cateData = res.category || [];
      });
    };

    return {
      rules,
      currentLocale,
      transportProtocolChange,
      submitLoading,
      certList,
      openDialog,
      onOpenAddCategory,
      handleAvatarSuccess,
      closeDialog,
      onCancel,
      onSubmit,
      network_server_type,
      getCategoryList,
      formRef,
      editCategoryRef,
      ...toRefs(state),
    };
  },
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
