<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    :rules="rules"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="60px">
      <el-form-item :label="$t('dataEnquiry.xm')" prop="projectId">
        <el-select
          v-model="form.projectId"
          size="small"
          multiple
          placeholder="请选择"
        >
          <el-option
            v-for="item in projectData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" size="small" @click="save">确 定</el-button>
      <el-button size="small" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { bindProject, getProjects } from '@/api/vehicle';
export default {
  data() {
    return {
      form: {
        imei: '',
        num: '',
        projectIds: '',
        projectId: [],
      },
      rules: {
        projectId: [
          { required: true, trigger: 'change', message: '请选择项目' },
        ],
      },
      projectData: [],
      clearable: true,
      title: '',
      dialogFormVisible: false,
    };
  },
  created() {},
  methods: {
    async getProjectData() {
      const { data } = await getProjects();
      this.projectData = data;
    },
    bindProduct(row) {
      this.title = '绑定项目';
      const projectIds = [];
      if (row.projects) {
        for (var i = 0; i < row.projects.length; i++) {
          projectIds.push(row.projects[i].id);
        }
      }
      this.form.projectId = projectIds;
      this.form.imei = row.imei;
      this.form.num = row.vehicleNumber;
      this.form.projectIds = projectIds.join(',');
      console.log(this.form);
      this.dialogFormVisible = true;
      this.getProjectData();
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      console.log(this.form);
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.form.projectIds = this.form.projectId.join(',');
          const { msg } = await bindProject(this.form);
          this.$notify({
            title: msg,
            type: 'success',
          });
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style>
.select {
  width: 100%;
}
</style>
