<template>
  <!-- 添加或修改套餐对话框 -->
  <el-dialog :title="title" :visible="open" width="800px" append-to-body @open="onOpen" @close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <form-col :span="span" label="所属用户" prop="userId" v-if="userType === UserType.ADMIN">
          <user-input v-model="form.userId" @change="onChangeUser" :disabled="hasView(views.user)"/>
        </form-col>
        <form-col :span="span" label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </form-col>
      </el-row>
      <el-row>
        <form-col :span="span" label="收费模式" prop="feeMode" >
          <el-select v-model="form.feeMode" style="width: 100%" @change="onChangeFeeMode">
            <el-option
              v-for="option of dict.type.suit_fee_mode"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </form-col>
        <form-col :span="span" label="收费方式" prop="feeType">
          <el-select v-model="form.feeType" style="width: 100%">
            <el-option
              v-for="option of dict.type.suit_fee_type"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="disabledFeeType(option)"
            />
          </el-select>
        </form-col>
        <form-col :span="span" label="价格" prop="price" v-if="[SuitFeeType.TIMING, SuitFeeType.COUNT].includes(form.feeType)">
          <el-input-number v-model="form.price" placeholder="请输入价格(元）" :min="0" :precision="2" controls-position="right" style="width: calc(100% - 2em)"/> 元
        </form-col>
        <form-col :span="span" label="通电时间" prop="value" v-if="form.feeType === SuitFeeType.TIMING">
          <el-input v-model="form.value" placeholder="请输入通电时间" type="number">
            <template #append>
              <el-select v-model="form.timeUnit" style="width: 6em">
                <el-option
                  v-for="option of dict.type.time_unit"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </template>
          </el-input>
        </form-col>
        <form-col :span="span" label="充值电量" prop="value" v-else-if="form.feeType === SuitFeeType.COUNT">
          <el-input v-model="form.value" placeholder="请输入度数" type="number">
            <template #append>度</template>
          </el-input>
        </form-col>
        <form-col :span="span" label="押金" prop="deposit" v-if="SuitFeeMode.SMART === form.feeMode">
          <el-input-number v-model="form.deposit" placeholder="请输入押金(元）" :min="0" :precision="2" controls-position="right" style="width: calc(100% - 2em)"/> 元
        </form-col>
        <form-col :span="span * 2" label="详细说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入详细说明" type="textarea" />
        </form-col>

        <el-col :span="24" v-if="[SuitFeeType.TIME_COUNT, SuitFeeType.TIME_TIMING].includes(form.feeType)">
          <suit-time-price
            :gear-amount.sync="form.gearAmount"
            :gear-time.sync="form.gearTime"
            :fee-type="form.feeType"
          />
        </el-col>

        <form-col :span="span * 2" label="应用设备" prop="deviceIds">
          <device-input v-model="form.deviceIds" multiple :before-open="beforeOpenDevice" :query="deviceQuery"/>
        </form-col>
      </el-row>
      <el-row v-if="SuitFeeType.eleList().includes(form.feeType)">
        <form-col :span="10" label="低功率关闭订单" prop="enabledLowPowerClose" label-width="9em">
          <el-switch v-model="form.enabledLowPowerClose" active-text="开启" inactive-text="关闭"/>
        </form-col>
        <form-col :span="14" label="功率阈值" prop="lowPower" v-if="form.enabledLowPowerClose">
          <el-input v-model="form.lowPower" placeholder="请输入功率阈值，低于该功率会自动关闭订单" type="number">
            <template #append>瓦</template>
          </el-input>
        </form-col>
      </el-row>
      <el-row v-if="SuitFeeType.TIMING === form.feeType">
        <form-col :span="10" label="时长语音播报" prop="enabledVoice" label-width="8em">
          <el-switch v-model="form.enabledVoice" active-text="开启" inactive-text="关闭"/>
        </form-col>
        <form-col :span="14" label="播报时机" prop="voiceMinutes" v-if="form.enabledVoice">
          <el-input v-model="form.voiceMinutes" placeholder="请输入播报时机" type="number">
            <template #append>分钟</template>
          </el-input>
        </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 { SmUserType, SuitFeeMode, SuitFeeType, UserType } from '@/utils/constants'
import DeviceInput from '@/components/Business/Device/DeviceInput.vue'
import { isEmpty } from '@/utils'
import { addSuit, getSuit, updateSuit } from '@/api/ss/suit'
import { $view } from '@/utils/mixins'
import UserInput from '@/components/Business/SmUser/UserInput.vue'
import { mapGetters } from 'vuex'
import SuitTimePrice from '@/views/ss/suit/component/SuitTimePrice.vue'

export default {
  name: "SuitEditDialog",
  mixins: [$view],
  components: { SuitTimePrice, UserInput, DeviceInput },
  dicts: ['time_unit', 'suit_fee_mode', 'suit_fee_type'],
  computed: {
    UserType() {
      return UserType
    },
    SmUserType() {
      return SmUserType
    },
    ...mapGetters(['userType']),
    SuitFeeMode() {
      return SuitFeeMode
    },
    SuitFeeType() {
      return SuitFeeType
    },
    // 设备查询条件
    deviceQuery() {
      return {
        userId: this.form.userId
      }
    },
    // 收费方式禁用的情况：单次收费，不支持分时段
    disabledFeeType() {
      return (option) => {
        return this.isDisabled(this.form.feeMode, option.value);
      }
    },
  },
  props: {
    title: {
      type: String,
      default: null,
    },
    open: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: null,
    },
    initForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    getApi: {
      type: Function,
      default: getSuit
    },
    updateApi: {
      type: Function,
      default: updateSuit,
    },
    addApi: {
      type: Function,
      default: addSuit
    }
  },
  data() {
    return {
      span: 12,
      // 表单参数
      form: {
        gearAmount: [],
        gearTime: []
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "所属用户不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        value: [
          { required: true, message: "通电时间/电量不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        deposit: [
          { required: true, message: "押金不能为空", trigger: "blur" }
        ],
        feeMode: [
          { required: true, message: "收费方式不能为空", trigger: "change" }
        ],
        feeType: [
          { required: true, message: "收费类型不能为空", trigger: "change" }
        ]
      }
    }
  },
  methods: {
    onOpen() {
      this.reset();
      this.amountIndex = null;
      if (this.id != null) {
        this.getApi(this.id).then(response => {
          let data = response.data;
          data.deviceIds = data.deviceList.map(item => item.deviceId);
          this.form = data;
        });
      }
    },
    // 表单重置
    reset() {
      this.form = {
        userId: this.initForm.userId,
        suitId: null,
        name: null,
        value: null,
        price: 0,
        deposit: 0,
        description: null,
        timeUnit: "3",
        deviceIds: this.initForm.deviceId ? [this.initForm.deviceId] : [],
        feeType: "1",
        feeMode: "1",
        gearAmount: [0,0,0,0],
        gearTime: [],
        enabledLowPowerClose: false,
        lowPower: 0,
      };
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    isDisabled(feeMode, value) {
      return feeMode === SuitFeeMode.SINGLE &&
        [SuitFeeType.TIME_COUNT, SuitFeeType.TIME_TIMING].includes(value)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.suitId != null) {
            this.updateApi(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
              this.$emit('success');
            });
          } else {
            this.addApi(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.$emit('success');
            });
          }
        }
      });
    },
    onChangeUser(nv) {
      if (!isEmpty(this.form.deviceIds)) {
        this.$message.info("由于切换了用户，请重新选择应用设备")
        this.form.deviceIds = []
      }
    },
    beforeOpenDevice() {
      if (this.form.userId == null) {
        this.$message.warning("请先选择所属用户");
        return false;
      }
      return true;
    },
    onChangeFeeMode(nv) {
      if(this.isDisabled(nv, this.form.feeType)) {
        this.form.feeType = null;
      }
    },
    // 取消按钮
    cancel() {
      this.$emit('update:open', false);
      this.reset();
    },

  }
}
</script>
