<template>
  <div>
    <span>{{ isEdit ? '编辑设备' : '添加设备' }}</span><el-button
      type="primary"
      size="mini"
      style="margin-left: 20px"
      @click="cancel"
    >返回</el-button>
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-position="left"
      label-width="140px"
      style="margin-top: 10px"
    >
      <TagCard v-auth="{ fieldName: 'deviceConfig' }" title="设备基本信息" style="margin-top: 20px;padding: 0 20px">
        <div class="wrap-content">
          <div v-auth="{ fieldName: 'deviceConfig', fieldValue: ['tenantId'] }" class="wrap-content__item">
            <el-form-item
              label="服务商平台名称"
              prop="tenantId"
              :required="false"
            >
              <el-select
                v-model="form.tenantId"
                placeholder="服务商平台名称"
                filterable
                style="width: 100%"
                clearable
                @change="onSelectChange('tenantId', $event)"
              >
                <el-option
                  v-for="(item, index) in merchantLists"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div
            v-if="form.tenantId"
            v-auth="{ fieldName: 'deviceConfig', fieldValue: ['tenantId'] }"
            class="wrap-content-detail"
            style="background: #dcdfe63d;"
          >
            <!--            <div class="wrap-content-detail__title">商户详情</div>-->
            <div class="wrap-content__item">
              <el-form-item label="设备appid" prop="deviceAppID">
                <el-input
                  v-model="form.tenantObj.deviceAppID"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="wrap-content__item">
              <el-form-item label="商户appid" prop="merchantAppID">
                <el-input
                  v-model="form.tenantObj.merchantAppID"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="wrap-content__item">
              <el-form-item label="商户平台地址" prop="merchantPlatformAddress">
                <el-input
                  v-model="form.tenantObj.merchantPlatformAddress"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="wrap-content__item">
              <el-form-item label="入库接口地址" prop="inboundInterfaceAddress">
                <el-input
                  v-model="form.tenantObj.inboundInterfaceAddress"
                  :disabled="true"
                />
              </el-form-item>
            </div>
          </div>
          <div v-else v-auth="{ fieldName: 'deviceConfig', fieldValue: ['tenantId'] }" class="wrap-content__item" />
          <div v-auth="{ fieldName: 'deviceConfig', fieldValue: ['ampeId'] }" class="wrap-content__item">
            <el-form-item label="Ampe平台名称" prop="ampeId" required>
              <el-select
                v-model="form.ampeId"
                placeholder="请选择Ampe平台名称"
                filterable
                style="width: 100%"
                clearable
                @change="onSelectChange('ampeId', $event)"
              >
                <el-option
                  v-for="(item, index) in ampeDataList"
                  :key="index"
                  :label="item.ampeName"
                  :value="item.ampeId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div
            v-if="form.ampeId"
            v-auth="{ fieldName: 'deviceConfig', fieldValue: ['ampeId'] }"
            class="wrap-content-detail"
            style="background: #dcdfe63d;"
          >
            <!--            <div class="wrap-content-detail__title">商户详情</div>-->
            <div class="wrap-content__item">
              <el-form-item label="产品ID" prop="productId">
                <el-input
                  v-model="form.apmeObj.productId"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="wrap-content__item">
              <el-form-item label="调用应用" prop="hostAppId">
                <el-input
                  v-model="form.apmeObj.hostAppId"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="wrap-content__item">
              <el-form-item label="小程序" prop="appId">
                <el-input
                  v-model="form.apmeObj.appId"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="wrap-content__item">
              <el-form-item label="小程序名称" prop="appName">
                <el-input
                  v-model="form.apmeObj.appName"
                  :disabled="true"
                />
              </el-form-item>
            </div>
          </div>
          <div v-else v-auth="{ fieldName: 'deviceConfig', fieldValue: ['ampeId'] }" class="wrap-content__item" />
        </div>
      </TagCard>
      <TagCard v-auth="{ fieldName: 'useConfig' }" title="使用配置" style="padding: 0 20px">
        <div class="wrap-content">
          <div v-auth="{ fieldName: 'useConfig', fieldValue: ['USE_EXPIRATION_DATE'] }" class="wrap-content__item">
            <el-form-item label="使用时间期限" prop="expirationDate">
              <el-date-picker
                v-model="form.expirationDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
                placeholder="请选择使用时间期限"
              />
            </el-form-item>
          </div>
        </div>
      </TagCard>
      <TagCard v-auth="{ fieldName: 'pushConfig' }" title="推送地址配置" style="padding: 0 20px">
        <div class="wrap-content">
          <div v-auth="{ fieldName: 'pushConfig', fieldValue: ['HEART_TRACKING_URL'] }" class="wrap-content__item">
            <el-form-item label="设备状态推送地址" prop="heartTrackingUrl">
              <!--            <el-input
                v-model="form.heartTrackingUrl"
                placeholder="请输入"
                maxlength="300"
              />-->
              <el-autocomplete
                v-model="form.heartTrackingUrl"
                popper-class="my-autocomplete"
                :fetch-suggestions="(queryString, cb) => querySearch('heartTrackingUrlList', queryString, cb)"
                placeholder="请输入内容"
                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>
      <TagCard v-auth="{ fieldName: 'systemConfig' }" title="系统配置" style="padding: 0 20px">
        <div class="wrap-content">
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['M_PASSWORD'] }" class="wrap-content__item">
            <el-form-item label="管理员密码" prop="mpassword">
              <el-input
                v-model="form.mpassword"
                placeholder="请输入"
                maxlength="50"
              />
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['VOLUME'] }" class="wrap-content__item">
            <el-form-item label="语音音量（1~100）" prop="volume">
              <el-input-number
                v-model="form.volume"
                size="mini"
                :min="1"
                :max="100"
              />
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['HIDE_NAVIGATION_BAR'] }" class="wrap-content__item">
            <el-form-item label="隐藏底部导航栏" prop="hideNavigationBar">
              <el-radio-group v-model="form.hideNavigationBar">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['FORBID_PULL_DOWN'] }" class="wrap-content__item">
            <el-form-item label="禁止下拉通知栏" prop="forbidPullDown">
              <el-radio-group v-model="form.forbidPullDown">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['AUTO_LAUNCH'] }" class="wrap-content__item">
            <el-form-item label="应用是否自启动" prop="autoLaunch">
              <el-radio-group v-model="form.autoLaunch">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['AUTOMATIC_ENTER_APPLET'] }" class="wrap-content__item">
            <el-form-item label="是否自动进入小程序" prop="automaticEnterApplet">
              <el-radio-group v-model="form.automaticEnterApplet">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['START_PAGE_URL'] }" class="wrap-content__item">
            <el-form-item label="启动页图片" prop="startPageUrl">
              <el-upload
                name="file"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="
                  (event) => {
                    doUploadAvatar(event, 'startPageUrl');
                  }
                "
                :before-upload="beforeAvatarUpload"
                :auto-upload="true"
                accept="image/png,image/gif,image/jpg,image/jpeg"
              >
                <img
                  v-if="!form.startPageUrl"
                  class="upload-img"
                  src="../../assets/K8-img.png"
                  alt=""
                >
                <div v-else class="upload-img">
                  <img :src="form.startPageUrl">
                  <span
                    class="del-img"
                    @click.stop="handleRemove('startPageUrl')"
                  >x</span>
                </div>
              </el-upload>
            </el-form-item>
          </div>
          <div v-auth="{ fieldName: 'systemConfig', fieldValue: ['HOME_PAGE_URL'] }" class="wrap-content__item">
            <el-form-item label="应用首页图片" prop="homePageUrl">
              <el-upload
                name="file"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="
                  (event) => {
                    doUploadAvatar(event, 'homePageUrl');
                  }
                "
                :before-upload="beforeAvatarUpload"
                :auto-upload="true"
                accept="image/png,image/gif,image/jpg,image/jpeg"
              >
                <!-- <div v-if="!form.homePageUrl" class="upload-default">
              <i class="avatar-uploader-icon el-icon-picture-outline" />
              <div class="el-upload__text">上传图片</div>
            </div> -->
                <img
                  v-if="!form.homePageUrl"
                  class="upload-img"
                  src="../../assets/WelcomeToUse.png"
                  alt=""
                >
                <!-- <i v-if="!form.homePageUrl" class="el-icon-plus avatar-uploader-icon" /> -->
                <div v-else class="upload-img">
                  <img :src="form.homePageUrl">
                  <span
                    class="del-img"
                    @click.stop="handleRemove('homePageUrl')"
                  >x</span>
                </div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </TagCard>
    </el-form>
    <div class="card-footer">
      <el-button style="width: 120px" @click="cancel"> 取消 </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 { pictureLocal } from '@/api/ordinary_user'
import { updateAuthAccount } from '@/api/HHAromeDeviceAuth'

export default {
  components: { TagCard },
  props: {
    merchantLists: {
      type: Array,
      default: () => []
    },
    ampeDataList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      heartTrackingUrlList: [
        // {
        //   value: 'https://hhomc.hz-hanghui.com:8096/middle-management/api/v1/device/heart/tracking',
        //   desc: 'OTA中台'
        // }
      ], // 设备状态推送地址输入建议
      form: {
        iotDeviceConfigId: null,
        // 设备状态推送地址
        heartTrackingUrl:
          'https://hhomc.hz-hanghui.com:8096/middle-management/api/v1/device/heart/tracking',
        mpassword: '142536',
        volume: 100, // 语音音量 0-100 默认值：100
        forbidPullDown: false, // 	禁止下拉通知栏 默认: false
        hideNavigationBar: false, // 隐藏底部导航栏 默认: false
        autoLaunch: false, // 应用是否自启动 默认: false
        automaticEnterApplet: false, // 是否自动进入小程序 默认: false
        startPageUrl: null, // 启动页图片
        homePageUrl: null, // 应用首页图片
        ampeId: null, // Ampe平台名称
        apmeObj: { // TODO ADD_FIELD
          productId: null, // 产品ID
          hostAppId: null, // 调用应用
          appId: null, // 小程序
          appName: null// 小程序名称
        },
        tenantId: null, // 服务商平台名称
        tenantObj: { // TODO ADD_FIELD
          deviceAppID: null, // 设备appId
          merchantAppID: null, // 商户appid
          merchantPlatformAddress: null, // 商户平台地址
          inboundInterfaceAddress: null// 入库接口地址
        },
        expirationDate: null // 使用时间期限
      },
      rules: {
        ampeId: [
          {
            required: true,
            message: '请选择Ampe平台名称!',
            trigger: ['change', 'blur']
          }
        ],
        tenantId: [
          {
            required: true,
            message: '请选择服务商平台名称!',
            trigger: ['change', 'blur']
          }
        ]
      },
      submitLoading: false,
      isEdit: false
    }
  },
  methods: {
    open(obj) {
      this.submitLoading = false
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (obj && Object.keys(obj).length > 0) {
          this.form = {
            ...obj,
            iotDeviceConfigId: obj.iotDeviceConfigId,
            forbidPullDown: obj.forbidPullDown, // 	禁止下拉通知栏 默认: false
            hideNavigationBar: obj.hideNavigationBar, // 隐藏底部导航栏 默认: false
            autoLaunch: obj.autoLaunch, // 应用是否自启动 默认: false
            automaticEnterApplet: obj.automaticEnterApplet, // 是否自动进入小程序 默认: false
            startPageUrl: obj.startPageUrl, // 启动页图片
            homePageUrl: obj.homePageUrl, // 应用首页图片
            ampeId: obj.ampeId, // Ampe平台名称
            tenantId: obj.tenantId, // 服务商平台名称
            expirationDate: obj.expirationDate // 使用时间期限
          }
          if (this.form.ampeId) {
            this.onSelectChange('ampeId', this.form.ampeId)
          }
          if (this.form.tenantId) {
            this.onSelectChange('tenantId', this.form.tenantId)
          }
          this.isEdit = true
        } else {
          this.isEdit = false
        }
      })
    },
    handleRemove(type) {
      if (type) {
        this.form[type] = null
      }
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      if (
        !(
          file.type === 'image/png' ||
          file.type === 'image/gif' ||
          file.type === 'image/jpg' ||
          file.type === 'image/jpeg'
        )
      ) {
        this.$notify.warning({
          title: '警告',
          message:
            '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于2M'
        })
        return
      }
    },
    doUploadAvatar(obj, type) {
      this.listLoading = true
      var avatar = new FormData()
      avatar.append('file', obj.file)
      pictureLocal(avatar).then((res) => {
        this.value = res.data
        this.listLoading = false
        this.$set(this.form, type, 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)
      }
    },
    // 状态切换
    onSelectChange(field, value) {
      console.log('onSelectChange', field, value)
      switch (field) {
        // Ampe平台名称
        case 'ampeId':
          if (value) {
            const item = (this.ampeDataList || []).filter(v => v.ampeId == value)[0] || {}
            console.log('ampeId', value, item)
            this.form.apmeObj = {
              productId: item.productId || '', // 产品ID
              hostAppId: item.hostAppId || '', // 调用应用
              appId: item.appId || '', // 小程序
              appName: item.appName || ''// 小程序名称
            }
          } else {
            console.log('ampeId', value)
            this.form.apmeObj = {
              productId: null, // 产品ID
              hostAppId: null, // 调用应用
              appId: null, // 小程序
              appName: null// 小程序名称
            }
          }
          break
        // 服务商平台名称
        case 'tenantId':
          if (value) {
            const item = (this.merchantLists || []).filter(v => v.id == value)[0] || {}
            console.log('tenantId', value, item)
            this.form.tenantObj = {
              deviceAppID: item.machineAppId || '', // 设备appId
              merchantAppID: item.serviceAppId || '', // 商户appid
              merchantPlatformAddress: item.serviceAddress || '', // 商户平台地址
              inboundInterfaceAddress: item.faceinAddress || ''// 入库接口地址
            }
          } else {
            console.log('tenantId', value)
            this.form.tenantObj = {
              deviceAppID: null, // 设备appId
              merchantAppID: null, // 商户appid
              merchantPlatformAddress: null, // 商户平台地址
              inboundInterfaceAddress: null// 入库接口地址
            }
          }
          break
      }
    },
    cancel() {
      this.$emit('cancel')
    },
    submit(e) {
      e.preventDefault()
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return false
        }
        if (this.submitLoading) {
          return
        }
        this.submitLoading = true
        try {
          await updateAuthAccount({
            ...this.form
          })
          this.$emit('success', this.isEdit)
        } catch (e) {
          // this.$refs.form.resetFields()
        } 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>
.auth-card {
  box-shadow: 0px 0px 6px 0px #99BDF366;
  background: #fff;
  border-radius: 12px;
  padding: 10px 20px;
  overflow: hidden;
  margin: 0 20px;
  height: auto;
}
.card-footer {
  margin-top: 20px;
  display: flex;
  width: 100%;
  justify-content: center;
}

.secondary_head {
  width: 130px;
  display: inline-block;
  position: relative;
  height: 40px;
  line-height: 40px;
  margin-left: 20px;
  &:before {
    position: absolute;
    top: 12px;
    left: -10px;
    width: 3px;
    height: 16px;
    content: "";
    background-color: #409eff;
    border-radius: 3px;
  }
  &:after {
    position: absolute;
    top: 12px;
    left: -16px;
    width: 3px;
    height: 16px;
    content: "";
    background-color: #409eff;
    border-radius: 3px;
  }
}
.wrap-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  &__item {
    width: calc(50% - 10px);
  }
}

.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;
    }
  }
}

.avatar-uploader .upload-default {
  border: 1px dashed #d9d9d9;
  border-radius: 0;
  cursor: pointer;
  width: 70px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.upload-default .avatar-uploader-icon {
  color: #8c939d;
  width: 22px;
  height: 18px;
  font-size: 20px;
  margin-top: 24px;
}
.upload-default .el-upload__text {
  margin-top: 8px;
  font-size: 14px;
  font-weight: 400;
  color: #ced3e3;
}
.upload-img {
  width: 50px;
  height: 91px;
  position: relative;
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    // border-radius: 12px;
  }
  .del-img {
    display: inline-block;
    width: 20px;
    height: 20px;
    background: #83878f;
    color: #fff;
    position: absolute;
    top: -12px;
    right: -10px;
    border-radius: 48%;
    line-height: 18px;
  }
}
</style>
