<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <div class="manage-container">
      <el-form
        ref="form"
        :model="form1"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="选择盒子">
          <el-select
            v-model="form1.id"
            multiple
            placeholder="请选择选择盒子"
            @change="boxChange"
          >
            <el-option
              v-for="item in boxData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <vab-query-form>
          <el-button type="primary" @click="save">
            {{ $t('defalult.tjtn') }}
          </el-button>
        </vab-query-form>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { fboxSync, boxList } from '@/api/device';
export default {
  data() {
    return {
      form: {},
      form1: {
        id: '',
      },
      projectId: '',
      boxData: [],
      dialogFormVisible: false,
      title: '',
    };
  },
  methods: {
    showSync(row) {
      this.projectId = row.projectId;
      this.dialogFormVisible = true;
      this.title = '盒子同步';
      this.getBoxList();
    },
    async getBoxList() {
      const { data } = await boxList();
      this.boxData = data;
    },
    boxChange() {
      const boxId = this.form1.id;
      const boxData = this.boxData;
      var selectBoxData = [];
      boxData.forEach(function (item, index) {
        if (boxId.includes(item.id)) {
          selectBoxData.push({
            id: item.id,
            code: item.code,
            name: item.name,
          });
        }
      });
      this.form = selectBoxData;
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          const { msg } = await fboxSync(this.form, this.projectId);
          this.$notify({
            title: msg,
            type: 'success',
          });
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
