<template>
  <el-dialog 
    :title="title" 
    :visible.sync="dialogVisible" 
    width="500px" 
    append-to-body 
    :close-on-click-modal="false"
    @open="handleOpen"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small" v-loading="loading">
      <el-row>
        <form-col :span="span" label="车型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入车型名称" />
        </form-col>
        <form-col :span="span" label="所属用户" prop="userId">
          <user-input 
            v-model="form.userId" 
            :text.sync="form.userName" 
            :disabled="!checkPermi(['system:user:list'])"
            @change="handleChangeUser"
          />
        </form-col>
        <form-col :span="span" label="满电电压" prop="fullVoltage">
          <el-input v-model="form.fullVoltage" placeholder="请输入满电电压" type="number">
            <template slot="append">V</template>
          </el-input>
        </form-col>
        <form-col :span="span" label="亏电电压" prop="lowVoltage">
          <el-input v-model="form.lowVoltage" placeholder="请输入亏电电压" type="number">
            <template slot="append">V</template>
          </el-input>
        </form-col>
        <form-col :span="span" label="满电续航" prop="fullEndurance">
          <el-input v-model="form.fullEndurance" placeholder="请输入满电续航" type="number">
            <template slot="append">KM</template>
          </el-input>
        </form-col>
        <form-col :span="span" label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </form-col>
        <form-col :span="span" label="低电量提醒开关" prop="lowBatteryReminderSwitch" label-width="9em">
          <el-switch v-model="form.lowBatteryReminderSwitch" />
        </form-col>
        <form-col :span="span" label="骑行低电量提醒" prop="lowBatteryReminder" label-width="9em" v-if="form.lowBatteryReminderSwitch">
          <el-input v-model="form.lowBatteryReminder" placeholder="请输入骑行低电量提醒" type="number">
            <template slot="append">%</template>
          </el-input>
        </form-col>
        <form-col :span="span" label="套餐" prop="suitIds">
          <suit-input 
            v-model="form.suitIds"
            :text="suitNames" 
            multiple
            :query="suitQuery"
            :before-open="beforeOpenSuit"
          />
        </form-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getModel, addModel, updateModel } from "@/api/bst/model";
import FormCol from "@/components/FormCol/index.vue";
import UserInput from '@/components/Business/User/UserInput.vue';
import AreaRemoteSelect from '@/components/Business/Area/AreaRemoteSelect.vue';
import { RoleKeys } from '@/utils/enums';
import SuitInput from '@/components/Business/Suit/SuitInput.vue';
import { mapGetters } from 'vuex';

export default {
  name: "ModelEditDialog",
  components: {
    FormCol,
    UserInput,
    AreaRemoteSelect,
    SuitInput
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: [String, Number],
      default: null
    },
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      RoleKeys,
      span: 24,
      title: '',
      form: {},
      rules: {
        areaId: [
          { required: true, message: "运营区不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "运营商不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "车型名称不能为空", trigger: "blur" }
        ],
        fullVoltage: [
          { required: true, message: "满电电压不能为空", trigger: "blur" }
        ],
        lowVoltage: [
          { required: true, message: "亏电电压不能为空", trigger: "blur" }
        ],
        fullEndurance: [
          { required: true, message: "满电续航不能为空", trigger: "blur" }
        ],
        lowBatteryReminderSwitch: [
          { required: true, message: "低电量提醒开关不能为空", trigger: "blur" }
        ],
        lowBatteryReminder: [
          { required: true, message: "骑行低电量提醒值不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userId']),
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    // 套餐查询条件
    suitQuery() {
      return {
        userId: this.form.userId
      }
    },
    suitNames() {
      if (this.form.suitList == null || this.form.suitList.length === 0) {
        return "";
      }
      return this.form.suitList.map(item => item.name).join(',');
    }
  },
  methods: {
    handleChangeUser() {
      if (this.form.suitIds != null && this.form.suitIds.length > 0) {
        this.form.suitIds = [];
        this.form.suitList = [];
        this.$message.warning("由于更换了所属用户，套餐数据已清空");
      }
    },
    beforeOpenSuit() {
      if (this.form.userId == null) {
        this.$modal.msgError("请先选择所属用户");
        return false;
      }
      return true;
    },
    handleOpen() {
      if (this.id == null) {
        this.reset();
        this.title = "添加车辆型号";
      } else {
        this.getDetail();
        this.title = "修改车辆型号";
      }
    },
    reset() {
      this.form = {
        id: null,
        areaId: null,
        userId: this.userId,
        name: null,
        fullVoltage: null,
        lowVoltage: null,
        fullEndurance: null,
        createTime: null,
        remark: null,
        deleted: null,
        lowBatteryReminderSwitch: false,
        lowBatteryReminder: null,
        // dto
        suitIds: [],
        // vo
        suitNames: null,
        // 初始化数据
        ...this.initData
      };
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },
    getDetail() {
      this.loading = true;
      getModel(this.id).then(response => {
        this.form = response.data;
      }).finally(() => {
        this.loading = false;
      });
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const promise = this.form.id != null ? updateModel(this.form) : addModel(this.form);
          promise.then(response => {
            this.$modal.msgSuccess(this.form.id != null ? "修改成功" : "新增成功");
            this.dialogVisible = false;
            this.$emit('success');
          });
        }
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.reset();
    }
  }
}
</script>

<style lang="scss" scoped>

</style> 