<template>
  <div class="app-container">
    <el-tabs tab-position="top">
      <el-tab-pane label="基本信息">
        <el-form
          ref="productRef"
          :model="form"
          :rules="rules"
          label-width="120px"
        >
          <!--          <el-row :gutter="100">-->
          <!--            <el-col :lg="12" :md="24" :sm="24" :xl="8" :xs="24">-->
          <!--            <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">-->
          <div
            :style="{
              padding: '0 200px',
              marginTop: '20px',
            }"
          >
            <el-form-item label="编码SN" prop="productSn">
              <el-input v-model="form.productSn" placeholder="请输入编码SN">
                <template #suffix>
                  <el-icon v-if="isProductSnUnique === true" color="green">
                    <SuccessFilled />
                  </el-icon>
                  <el-icon v-else-if="isProductSnUnique === false" color="red">
                    <CircleCloseFilled />
                  </el-icon>
                  <el-icon v-else>
                    <InfoFilled />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
              <el-tree-select
                v-model="form.categoryId"
                :data="categoryOptions"
                :props="{
                  value: 'categoryId',
                  label: 'name',
                  children: 'children',
                }"
                check-strictly
                clearable
                placeholder="请选择产品分类"
                value-key="categoryId"
              />
            </el-form-item>
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" clearable>
                <el-option :value="1" label="直连设备" />
                <el-option :value="2" label="网关子设备" />
                <el-option :value="3" label="网关设备" />
              </el-select>
            </el-form-item>
            <el-form-item label="厂商" prop="companyName">
              <el-input
                v-model="form.companyName"
                placeholder="请输入厂商名称"
              />
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
            <el-form-item label="描述" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入描述"
                type="textarea"
              />
            </el-form-item>
            <el-form-item label="图片地址" prop="imgUrl">
              <!--                <el-input v-model="form.imgUrl" placeholder="请输入图片地址" />-->
              <image-upload v-model="form.imgUrl" :limit="1"></image-upload>
            </el-form-item>
            <el-form-item style="text-align: center; margin: 40px 0px">
              <el-button
                v-if="form.status !== 2"
                type="primary"
                @click="submitForm"
                >提交
              </el-button>
            </el-form-item>
          </div>

          <!--              <el-form-item label="租户" prop="tenantId">-->
          <!--                <el-tooltip content="在此输入搜索关键字" effect="light" placement="right">-->
          <!--                  <el-select-->
          <!--                    v-model="form.tenantId"-->
          <!--                    :remote-method="getTenantList"-->
          <!--                    filterable-->
          <!--                    placeholder="请选择租户"-->
          <!--                    remote-->
          <!--                    remote-show-suffix-->
          <!--                  >-->
          <!--&lt;!&ndash;                    @blur="showTenantTip=false"&ndash;&gt;-->
          <!--                    &lt;!&ndash;                    @focus="showTenantTip=true"&ndash;&gt;-->
          <!--                    <el-option-->
          <!--                      v-for="item in tenantOptions"-->
          <!--                      :key="item.tenantId"-->
          <!--                      :label="item.tenantName"-->
          <!--                      :value="item.tenantId"-->
          <!--                    />-->
          <!--                  </el-select>-->
          <!--                </el-tooltip>-->

          <!--              </el-form-item>-->

          <!--            </el-col>-->
          <!--            <el-col :lg="12" :md="24" :sm="24" :xl="8" :xs="24">-->
          <!--              <el-form-item label="产品编码SN" prop="productSn">-->
          <!--                <el-input-->
          <!--                  v-model="form.productSn"-->
          <!--                  placeholder="请输入产品编码SN"-->
          <!--                >-->
          <!--                  <template #suffix>-->
          <!--                    <el-icon v-if="isProductSnUnique === true" color="green">-->
          <!--                      <SuccessFilled />-->
          <!--                    </el-icon>-->
          <!--                    <el-icon-->
          <!--                      v-else-if="isProductSnUnique === false"-->
          <!--                      color="red"-->
          <!--                    >-->
          <!--                      <CircleCloseFilled />-->
          <!--                    </el-icon>-->
          <!--                    <el-icon v-else>-->
          <!--                      <InfoFilled />-->
          <!--                    </el-icon>-->
          <!--                  </template>-->
          <!--                </el-input>-->
          <!--              </el-form-item>-->
          <!--&lt;!&ndash;              <el-form-item label="mqtt账号" prop="mqttAccount">&ndash;&gt;-->
          <!--&lt;!&ndash;                <el-input&ndash;&gt;-->
          <!--&lt;!&ndash;                  v-model="form.mqttAccount"&ndash;&gt;-->
          <!--&lt;!&ndash;                  placeholder="请输入mqtt账号"&ndash;&gt;-->
          <!--&lt;!&ndash;                />&ndash;&gt;-->
          <!--&lt;!&ndash;              </el-form-item>&ndash;&gt;-->
          <!--&lt;!&ndash;              <el-form-item label="mqtt密码" prop="mqttPassword">&ndash;&gt;-->
          <!--&lt;!&ndash;                <el-input&ndash;&gt;-->
          <!--&lt;!&ndash;                  v-model="form.mqttPassword"&ndash;&gt;-->
          <!--&lt;!&ndash;                  placeholder="请输入mqtt密码"&ndash;&gt;-->
          <!--&lt;!&ndash;                  type="password"&ndash;&gt;-->
          <!--&lt;!&ndash;                />&ndash;&gt;-->
          <!--&lt;!&ndash;              </el-form-item>&ndash;&gt;-->
          <!--&lt;!&ndash;              <el-form-item label="产品秘钥" prop="mqttSecret">&ndash;&gt;-->
          <!--&lt;!&ndash;                <el-input&ndash;&gt;-->
          <!--&lt;!&ndash;                  v-model="form.mqttSecret"&ndash;&gt;-->
          <!--&lt;!&ndash;                  placeholder="请输入产品秘钥"&ndash;&gt;-->
          <!--&lt;!&ndash;                  type="password"&ndash;&gt;-->
          <!--&lt;!&ndash;                />&ndash;&gt;-->
          <!--&lt;!&ndash;              </el-form-item>&ndash;&gt;-->
          <!--&lt;!&ndash;              <el-form-item label="认证方式" prop="vertificateMethod">&ndash;&gt;-->
          <!--&lt;!&ndash;                <el-select&ndash;&gt;-->
          <!--&lt;!&ndash;                  v-model="form.vertificateMethod"&ndash;&gt;-->
          <!--&lt;!&ndash;                  placeholder="请选择认证方式"&ndash;&gt;-->
          <!--&lt;!&ndash;                >&ndash;&gt;-->
          <!--&lt;!&ndash;                  <el-option&ndash;&gt;-->
          <!--&lt;!&ndash;                    v-for="[value, key] in vertificateMethodOptions"&ndash;&gt;-->
          <!--&lt;!&ndash;                    :key="value"&ndash;&gt;-->
          <!--&lt;!&ndash;                    :label="key"&ndash;&gt;-->
          <!--&lt;!&ndash;                    :value="value"&ndash;&gt;-->
          <!--&lt;!&ndash;                  />&ndash;&gt;-->
          <!--&lt;!&ndash;                </el-select>&ndash;&gt;-->
          <!--&lt;!&ndash;              </el-form-item>&ndash;&gt;-->
          <!--            </el-col>-->
          <!--            <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">-->

          <!--              <el-form-item label="mqtt账号" prop="mqttAccount">-->
          <!--                <el-input-->
          <!--                  v-model="form.mqttAccount"-->
          <!--                  placeholder="请输入mqtt账号"-->
          <!--                />-->
          <!--              </el-form-item>-->
          <!--              <el-form-item label="mqtt密码" prop="mqttPassword">-->
          <!--                <el-input-->
          <!--                  v-model="form.mqttPassword"-->
          <!--                  placeholder="请输入mqtt密码"-->
          <!--                  type="password"-->
          <!--                />-->
          <!--              </el-form-item>-->
          <!--              <el-form-item label="产品秘钥" prop="mqttSecret">-->
          <!--                <el-input-->
          <!--                  v-model="form.mqttSecret"-->
          <!--                  placeholder="请输入产品秘钥"-->
          <!--                  type="password"-->
          <!--                />-->
          <!--              </el-form-item>-->
          <!--              <el-form-item label="认证方式" prop="vertificateMethod">-->
          <!--                <el-select-->
          <!--                  v-model="form.vertificateMethod"-->
          <!--                  placeholder="请选择认证方式"-->
          <!--                >-->
          <!--                  <el-option-->
          <!--                    v-for="[value, key] in vertificateMethodOptions"-->
          <!--                    :key="value"-->
          <!--                    :label="key"-->
          <!--                    :value="value"-->
          <!--                  />-->
          <!--                </el-select>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--            <el-col :lg="12" :md="24" :sm="24" :xl="8" :xs="24">-->

          <!--            </el-col>-->
          <!--          </el-row>-->
          <!--          <el-col :span="20">-->

          <!--          </el-col>-->
        </el-form>
      </el-tab-pane>
      <el-tab-pane :disabled="!form.productId" label="产品模型" lazy>
        <model
          v-if="form.productId"
          ref="modelRef"
          :model-json="form.thingsModelsJson"
          :product="form"
          :product-id="form.productId"
          @model-updated="getData"
        />
      </el-tab-pane>
      <el-tab-pane :disabled="!form.productId" label="固件管理" lazy>
        <firmware v-if="form.productId" :product-id="form.productId" />
      </el-tab-pane>
      <el-tab-pane :disabled="!form.productId" label="告警配置" lazy>
        <alert
          v-if="form.productId"
          :product="form"
          :product-id="form.productId"
        />
      </el-tab-pane>
      <el-tab-pane :disabled="!form.productId" label="设备列表" lazy>
        <device v-if="form.productId" :product-id="form.productId"></device>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import Firmware from "@/views/product/firmware/index.vue";
import Device from "@/views/iot/device/index.vue";
import { onMounted, reactive, ref, toRefs } from "vue";
import Model from "@/views/product/product/panes/model.vue";
import { useRoute } from "vue-router";
import {
  addProduct,
  checkProductSn,
  getProduct,
  updateProduct,
} from "@/api/product/product";
import { listCategory } from "@/api/product/category";
import { listTenant } from "@/api/system/tenant";
import ImageUpload from "@/components/ImageUpload/index.vue";
import { ElMessage } from "element-plus";
import tab from "@/plugins/tab";
import { debounce } from "lodash-es";
import Alert from "@/views/product/alertRule/index.vue";

const checkProductSnUnique = debounce((rule, value, callback) => {
  if (!value) {
    callback();
    isProductSnUnique.value = undefined;
    return;
  }
  if (value === oriSn.value) {
    callback();
    return;
  }
  checkProductSn(value)
    .then((response) => {
      const isUnique = response.data;
      if (isUnique) {
        isProductSnUnique.value = true;
        callback();
      } else {
        isProductSnUnique.value = false;
        callback(new Error("产品编码SN重复"));
      }
    })
    .catch((e) => {
      callback(new Error("检查重复失败"));
    });
}, 500);
const route = useRoute();
const data = reactive({
  form: {},
  rules: {
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" },
    ],
    categoryId: [
      { required: true, message: "产品分类ID不能为空", trigger: "blur" },
    ],
    tenantId: [{ required: true, message: "租户ID不能为空", trigger: "blur" }],
    productSn: [
      {
        validator: checkProductSnUnique,
        trigger: "change",
      },
      {
        required: true,
        message: "产品编号SN不能为空",
        trigger: "blur",
      },
    ],
    deviceType: [
      {
        required: true,
        message: "设备类型不能为空",
        trigger: "change",
      },
    ],
  },
});

const { form, rules } = toRefs(data);
const productRef = ref();
const categoryOptions = ref([]); // 产品分类树形选择
const tenantOptions = ref([]);
const isProductSnUnique = ref();
const showTenantTip = ref(false);

// 表单重置
function reset() {
  form.value = {
    productId: null,
    productSn: null,
    productName: null,
    categoryId: null,
    tenantId: null,
    mqttAccount: null,
    mqttPassword: null,
    mqttSecret: null,
    status: null,
    thingsModelsJson: null,
    deviceType: null,
    vertificateMethod: null,
    model: null,
    companyName: null,
    imgUrl: null,
    createBy: null,
    createTime: null,
    remark: null,
  };
  // proxy.resetForm("productRef");
  if (productRef.value) {
    productRef.value.resetFields();
  }
}

// 获取产品详情, 回显表单
const oriSn = ref(""); // 自己的sn
const getData = () => {
  reset();
  const _productId = route.query.productId;
  if (_productId) {
    const tabObj = Object.assign({}, route, { title: "修改产品" });
    tab.updatePage(tabObj);
    getProduct(_productId).then((response) => {
      form.value = response.data;
      oriSn.value = response.data.productSn;
    });
  } else {
    const tabObj = Object.assign({}, route, { title: "新增产品" });
    tab.updatePage(tabObj);
  }
};
const getCategoryList = async () => {
  const response = await listCategory();
  categoryOptions.value = response.data;
};

const getTenantList = async (keyword) => {
  const response = await listTenant({
    pageNum: 1,
    pageSize: 20,
    tenantName: keyword,
  });
  tenantOptions.value = response.rows;
};
const submitForm = () => {
  productRef.value.validate((valid) => {
    if (valid) {
      if (valid) {
        if (form.value.productId != null) {
          updateProduct(form.value).then((response) => {
            ElMessage.success("修改成功");
          });
        } else {
          addProduct(form.value).then((response) => {
            ElMessage.success("新增成功");
            form.value = response.data;
            // const tabObj = Object.assign({}, route, { title: "修改产品" });
            // tab.updatePage(tabObj);
            const tabObj = { path: "/produc/product" };
            tab.closeOpenPage(tabObj);
          });
        }
      }
    }
  });
};
onMounted(() => {
  getData();
});

getCategoryList();
// getTenantList();
</script>

<style lang="scss" scoped>
:deep(.el-tabs__nav-wrap) {
  overflow: unset;

  .el-tabs__nav-scroll {
    overflow: unset;
    display: flex;
    justify-content: center;
  }
}

:deep(.el-tabs__item.is-disabled) {
  &:hover {
    //cursor: url("../../../assets/images/model-alert.svg"), not-allowed;
  }

  &:hover::before {
    content: "请先添加产品";
    position: absolute;
    background-color: tomato;
    line-height: 1;
    color: #fff;
    padding: 4px;
    border-radius: 4px;
    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
    display: block;
    left: 50%;
    transform: translateX(-50%);
    top: 110%;
    backdrop-filter: blur(16px);
  }
}
</style>
