<template>
  <div>
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-position="left"
      label-width="200px"
      style="margin-top: 10px"
    >
      <TagCard title="设备基本信息">
        <div class="wrap-content">
          <div class="wrap-content__item">
            <el-form-item label="设备sn" prop="sn" required>
              <!-- :disabled="isDis" -->
              <el-input
                v-model="form.sn"
                placeholder="请输入设备sn"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item label="购买方公司名称" prop="purchaserId">
              <el-select
                v-model="form.purchaserId"
                placeholder="请选择购买方公司名称"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(item, index) in buyList"
                  :key="index"
                  :label="item.companyName"
                  :value="item.purchaserId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item label="应用类型" prop="applicationTypeId">
              <el-select
                v-model="form.applicationTypeId"
                placeholder="请选择应用类型"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(item, index) in applicationList"
                  :key="index"
                  :label="item.applicationType"
                  :value="item.applicationTypeId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="设备型号（硬件）"
              prop="deviceModelHardwareId"
            >
              <el-select
                v-model="form.deviceModelHardwareId"
                placeholder="请选择设备型号（硬件）"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(item, index) in deviceList"
                  :key="index"
                  :label="item.deviceModel"
                  :value="item.deviceModelId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="设备型号（环境）"
              prop="deviceModelEnvironmentId"
            >
              <el-select
                v-model="form.deviceModelEnvironmentId"
                placeholder="请选择设备型号（环境）"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(item, index) in deviceList"
                  :key="index"
                  :label="item.deviceModel"
                  :value="item.deviceModelId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item label="系统类型" prop="systemTypeCode">
              <el-select
                v-model="form.systemTypeCode"
                placeholder="请选择系统类型"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(item, index) in systemType"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
      </TagCard>
      <TagCard title="三方接口接入配置">
        <div class="wrap-content">
          <div class="wrap-content__item">
            <el-form-item label="ws地址" prop="websocketSubscribeUrl">
              <el-autocomplete
                v-model="form.websocketSubscribeUrl"
                popper-class="my-autocomplete"
                :fetch-suggestions="(queryString, cb) => querySearch('websocketSubscribeUrlList', queryString, cb)"
                placeholder="请输入地址"
                clearable
                style="width: 100%"
              >
                <template slot-scope="{ item }">
                  <div class="name">{{ item.value }}</div>
                  <span class="addr">{{ item.desc }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </div>
        </div>
      </TagCard>
    </el-form>
    <div class="card-footer">
      <el-button style="width: 120px" @click="back"> 取消 </el-button>
      <el-button type="primary" style="width: 120px" :loading="submitLoading" @click="submit">
        确定
      </el-button>
    </div>
  </div>
</template>

<script>
import TagCard from '@/components/TagCard'
import { add } from '@/api/HHOMCDevice.js'
import { applicationTypeList, deviceModelList, purchaserList } from '@/api/configuration'

export default {
  components: { TagCard },
  props: {
    obj: {
      type: Object,
      default: () => {}
    },
    templateData: {
      type: Object,
      default: () => {}
    },
    isDis: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        sn: null, // 设备sn
        purchaserId: null, // 购买方公司名称
        applicationTypeId: null, // 应用类型
        deviceModelHardwareId: null, // 设备型号（硬件）
        deviceModelEnvironmentId: null, // 设备型号（环境）
        systemTypeCode: null, // 系统类型
        websocketSubscribeUrl: '' // ws地址
      },
      rules: {
        sn: [
          {
            required: true,
            whitespace: true,
            message: '不能为空!',
            trigger: ['change', 'blur']
          }
        ]
      },
      submitLoading: false,
      websocketSubscribeUrlList: [
        {
          value: 'wss://hhomc.hz-hanghui.com:18096/',
          desc: '塘栖域名地址'
        }, {
          value: 'ws://115.227.34.58:19086/',
          desc: '塘栖IP地址'
        }
      ], // ws地址输入建议
      applicationList: [], // 应用类型下拉
      deviceList: [], // 设备型号下拉
      buyList: [], // 购买方公司名称下拉
      // 系统类型下拉
      systemType: [
        { id: 1, name: '蚂蚁OS' },
        { id: 2, name: '非蚂蚁OS' }
      ]
    }
  },
  watch: {
    templateData() {
      console.log(this.templateData)
      if (this.templateData != {}) {
        this.form = {
          ...this.templateData,
          sn: this.form.sn,
          purchaserId: this.form.purchaserId,
          id: this.form.id
        }
        // this.form.sn = this.obj.sn;
      }
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      this.getApplicationTypeList()
      this.getDeviceModelList()
      this.getPurchaserList()
      this.$nextTick(() => {
        if (this.obj) {
          console.log(this.obj)
          this.form = {
            ...this.obj
          }
        }
      })
    },
    // 获取应用类型列表
    getApplicationTypeList() {
      applicationTypeList().then((res) => {
        this.applicationList = res.data
      })
    },
    // 设备型号列表
    getDeviceModelList() {
      deviceModelList().then((res) => {
        this.deviceList = res.data
      })
    },
    // 购买方列表
    getPurchaserList() {
      purchaserList().then((res) => {
        this.buyList = res.data
      })
    },
    querySearch(field, queryString, cb) {
      const restaurants = this[field]
      const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    back() {
      this.$emit('back')
    },
    submit(e) {
      e.preventDefault()
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return false
        }
        if (this.submitLoading) {
          return
        }
        this.submitLoading = true
        try {
          console.log(this.form)
          await add(this.form)
          this.$message({
            message: `${this.form.id ? '修改' : '添加'}成功!`,
            type: 'success'
          })
          this.$emit('back')
        } catch (e) {
          console.info('add', e)
        } finally {
          this.submitLoading = false
        }
      })
    }
  }
}
</script>

<style lang="scss" >
.my-autocomplete {
  li {
    padding: 5px 20px !important;

    .name {
      line-height: 20px !important;
      white-space: pre-wrap; /* 保留空白符，如果内容超过容器宽度则换行 */
      overflow-wrap: break-word; /* 在长单词或URL地址内部进行换行 */
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
<style lang="scss" scoped>
.card-footer {
  margin-top: 20px;
  display: flex;
  width: 100%;
  justify-content: center;
}
.wrap-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  &__item {
    width: calc(50% - 10px);
    padding: 10px 10px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
  }
}
.wrap-content-detail {
  width: calc(100%);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  position: relative;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 10px;
  box-sizing: border-box;
  overflow: hidden;
  margin-bottom: 10px;
  &__title {
    position: absolute;
    background: white;
    height: 40px;
    line-height: 40px;
    top: -20px;
    z-index: 999;
    padding: 0 10px;
  }
  &__item {
    width: calc(50% - 10px);
    .el-form-item {
      padding: 10px 0px;
      margin-bottom: 0px !important;
    }
  }
}

</style>
