<template>
  <div class="app-container">
    <el-form :model="form" :rules="rules" ref="form" label-width="auto" :disabled="disabled">
      <el-form-item label="设备型号：" prop="clientType">
        <el-input v-model="form.clientType" placeholder="请输入设备型号" />
      </el-form-item>
      <el-form-item label="设备名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入设备名称" />
      </el-form-item>
      <el-form-item label="蓝牙名称：" prop="bluetoothName">
        <el-input v-model="form.bluetoothName" placeholder="请输入蓝牙名称" />
      </el-form-item>
      <el-form-item label="制造商：" prop="manufacturer">
        <el-select v-model="form.manufacturer" placeholder="请选择设备制造商" clearable>
          <el-option v-for="item in manuOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备分类：" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择设备分类">
          <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型：" prop="deviceType">
        <el-select v-model="form.deviceType" placeholder="请选择设备类型">
          <el-option v-for="item in deviceTypeOptions" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否热门：" prop="isHot">
        <el-select v-model="form.isHot" placeholder="请选择是否热门">
          <el-option v-for="item in hotOptions" :key="item.value" :label="item.label" :value="Number(item.value)" />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="在线图片：" prop="img">
            <Upload listType="picture-card" :url="form.img" @upload="handleUploadImg($event, 'online')"
              :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="离线图片：" prop="offlineImg" style="float:right">
            <Upload listType="picture-card" :url="form.offlineImg" @upload="handleUploadImg($event, 'offline')"
              :disabled="disabled" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表单 -->
      <el-button v-if="disabled === false && form.typeList.length < 4" type="primary" icon="el-icon-plus"
        @click="getAdd">新增</el-button>
      <div class="sub-form" v-for="(item, index) in form.typeList" :key="item.id">
        <el-form-item label="设备模式：" :prop="`typeList.${index}.type`"
          :rules="{ required: true, message: '请选择设备模式', trigger: 'change' }">
          <el-select v-model="item.type" placeholder="请选择设备模式" @change="getTypeChange(item)">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="Number(item.value)"
              :disabled="item.disabled" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="item.type !== 3" label="功能权限：" :prop="`typeList.${index}.functionList`"
          :rules="{ type: 'array', required: true, message: '请选择功能权限', trigger: 'change' }">
          <el-select v-model="item.functionList" placeholder="请选择功能权限" multiple>
            <el-option v-for="item in functionOptions" :key="item.id" :label="item.name" :value="item.type" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="item.type == 2" label="连接方式：" :prop="`typeList.${index}.connectType`"
          :rules="{ required: true, message: '请选择连接方式', trigger: 'change' }">
          <el-select v-model="item.connectType" placeholder="请选择连接方式">
            <el-option v-for="item in connectTypeOptions" :key="item.value" :label="item.label"
              :value="Number(item.value)" />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="item.type === 1 || item.type === 3 ? '连接引导图：' : '开机引导图：'"
              :prop="`typeList.${index}.icon1`" :rules="{ required: true, message: '请上传引导图片', trigger: 'change' }">
              <Upload listType="picture-card" :url="item.icon1" @upload="handleUploadIcon($event, index, 'icon1')"
                :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配对键引导图：" :prop="`typeList.${index}.icon2`" style="float:right"
              :rules="{ required: true, message: '请上传配对键引导图', trigger: 'change' }">
              <Upload listType="picture-card" :url="item.icon2" @upload="handleUploadIcon($event, index, 'icon2')"
                :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="item.type === 1 || item.type === 3" label="引导页内容："
          :prop="`typeList.${index}.guidePageContent`" :rules="{ required: true, message: '请输入引导页内容', trigger: 'blur' }">
          <Editor v-model="item.guidePageContent" :min-height="250" :readOnly="disabled" />
        </el-form-item>
        <!-- 删除按钮 -->
        <el-link class="el-icon-close" v-if="form.typeList.length > 1" :underline="false" @click="getDelete(index)" />
      </div>
    </el-form>
    <div style="margin-left: 120px;">
      <el-button @click="getCancel">取消</el-button>
      <el-button v-if="disabled === false" type="primary" @click="getSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { categoryList } from "@/api/device/category";
import { functionList } from "@/api/device/function";
import { Add, Detail, Edit } from "@/api/device/list";
import { devTypeMixin } from "@/mixin/index";
import Editor from "@/components/Editor/index";

export default {
  mixins: [devTypeMixin],
  components: {
    Editor
  },
  data() {
    return {
      // 能否编辑
      disabled: false,
      functionOptions: [],
      // 表单
      form: {
        typeList: [
          {
            functionList: [],
          },
        ],
      },
      // 表单验证
      rules: {
        clientType: [{ required: true, message: "请输入设备型号", trigger: "blur" }],
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        bluetoothName: [{ required: true, message: '请输入蓝牙名称', trigger: 'blur' }],
        isHot: [{ required: true, message: "是否热门", trigger: "change" }],
        categoryId: [{ required: true, message: "请选择设备分类", trigger: "change" }],
        deviceType: [{ required: true, message: "请选择设备类型", trigger: 'change' }],
        img: [{ required: true, message: "请上传在线图片", trigger: "change" }],
        offlineImg: [{ required: true, message: "请上传离线图片", trigger: "change" }],
      },
      // 是否热门
      hotOptions: [{
        value: 0,
        label: '否'
      }, {
        value: 1,
        label: '是'
      }],
      // 设备连接
      connectTypeOptions: [{
        value: 2,
        label: 'UPnP'
      }, {
        value: 3,
        label: 'MQTT'
      }],
      // 制造商
      manuOptions: [{
        value: 'ShanJing',
        label: 'ShanJing'
      }, {
        value: 'JieLi',
        label: 'JieLi'
      }, {
        value: 'LingXin',
        label: 'LingXin'
      }, {
        value: 'QiXinWei',
        label: 'QiXinWei'
      }],
      functionOptions: [],
      categoryOptions: [],
      deviceTypeOptions: [{
        value: 0,
        label: '音响'
      }, {
        value: 1,
        label: '耳机'
      }, {
        value: 2,
        label: '穿戴'
      }]
    };
  },
  mounted() {
    this.disabled = this.$route.query.key === "查看" ? true : false
    this.getList()
    // 权限列表
    functionList({
      isDelete: 0
    }).then((res) => {
      if (res.code === 0) {
        this.functionOptions = res.data;
      }
    });
    // 设备类型
    categoryList({
      status: 1,
    }).then((res) => {
      if (res.code === 0) {
        this.categoryOptions = res.data;
      }
    });
  },
  methods: {
    // 详情
    getList() {
      if (this.$route.query.id) {
        Detail({
          id: this.$route.query.id,
        }).then((res) => {
          if (res.code === 0) {
            this.form = res.data;
            this.form.typeList.map((i) => {
              this.typeOptions[i.type - 1].disabled = true;
            });
          }
        });
      }
    },

    // 上传设备图片
    handleUploadImg(e, key) {
      key === "online"
        ? (this.form.img = e.file)
        : (this.form.offlineImg = e.file);
    },

    // 上传设备图标
    handleUploadIcon(e, index, obj) {
      this.form.typeList[index][obj] = e.file;
    },

    // 选中一个设备类型就从数组中去掉
    getTypeChange(item) {
      for (let i in this.typeOptions) {
        this.typeOptions[i].disabled = false
      }
      this.$set(item, 'functionList', [])
      this.$set(item, 'connectType', null)
      this.$set(item, 'guidePageContent', '')
      this.form.typeList.map(i => {
        if (i.type) {
          let index = this.typeOptions.findIndex(j => j.value == i.type)
          this.typeOptions[index].disabled = true
        }
      })
    },

    // 新增子表单
    getAdd() {
      this.form.typeList.push({
        type: "",
        functionList: [],
        icon1: "",
        icon2: "",
      });
    },

    // 删除子表单
    getDelete(index) {
      this.form.typeList.splice(index, 1);
      this.typeOptions[index].disabled = false;
    },

    // 取消
    getCancel() {
      this.$tab.closeOpenPage("/device/deviceList");
    },

    // 提交
    getSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.$route.query.id) {
            // 编辑
            Edit(this.form).then((res) => {
              if (res.code === 0) {
                this.$message.success("修改成功！");
                this.getCancel();
              }
            });
          } else {
            // 新建
            Add(this.form).then((res) => {
              if (res.code === 0) {
                this.$message.success("提交成功！");
                this.getCancel();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  width: 580px;
}

.sub-add {
  position: absolute;
  top: 0;
  right: -100px;
}

.sub-form {
  position: relative;
  border: 1px solid #e8e8e8;
  padding: 25px 25px 0 0;
  margin-bottom: 20px;

  .el-icon-close {
    position: absolute;
    top: 5px;
    right: 5px;
    color: #c0c4cc;
  }
}
</style>