<template>
  <div class='app-container'>
    <el-form :model="form" :rules="rules" ref="form" label-width="100px" :disabled="disabled">
      <el-form-item label="活动名称：">
        <el-input v-model="form.name" placeholder="请输入活动名称" />
      </el-form-item>
      <el-form-item label="活动图片：" prop="pic">
        <Upload listType="picture-card" :url="form.pic" @upload="upload" />
      </el-form-item>
      <el-form-item label="有效时间：" prop="timeList">
        <el-date-picker type="datetimerange" v-model="form.timeList" start-placeholder="开始日期" end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss" />
      </el-form-item>
      <el-form-item label="活动设备：" style="width: 1000px" prop="deviceRespList">
        <el-button type="primary" icon="el-icon-plus" @click="handlePush" :disabled="disabledActivity">添加</el-button>
        <el-table :data="form.deviceRespList">
          <el-table-column label="关联设备" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-form-item :prop="`deviceRespList.${scope.$index}.deviceId`"
                :rules="{ required: true, trigger: 'change' }">
                <span v-if="disabledActivity">{{ devOptions.find(i => i.value == scope.row.deviceId).label }}</span>
                <el-select v-else v-model="scope.row.deviceId" filterable placeholder="请选择关联设备" :disabled="disabledActivity">
                  <el-option v-for="item in devOptions" :key="item.value" :value="item.value" :label="item.label"
                    :disabled="item.disabled" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="活动权益" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="`deviceRespList.${scope.$index}.indate`"
                :rules="{ required: true, trigger: 'change' }">
                <el-select v-model="scope.row.indate" placeholder="请选择活动权益" :disabled="disabledActivity">
                  <el-option v-for="item in serviceTimeOptions" :key="item.value" :value="item.value"
                    :label="item.label" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="领取数量" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="`deviceRespList.${scope.$index}.totalNum`"
                :rules="[{ type: 'number', required: true, min: disabledActivity && num[scope.$index] ? num[scope.$index] : 1, trigger: 'blur' }]">
                <el-input-number v-model="scope.row.totalNum" :controls="false" :min="1" placeholder="请输入领取数量"
                  @change="handleChange($event, scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="delete" @click="getDelete(scope.row.deviceId, scope.$index)"
                :disabled="disabledActivity">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div class="form-btn">
      <el-button @click="cancel">取消</el-button>
      <el-button v-if="!disabled" type="primary" @click="getSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { detail, submit } from "@/api/operation/activity"
import { serviceTimeMixin, devMixin } from '@/mixin/index'
export default {
  mixins: [serviceTimeMixin, devMixin],
  data() {
    return {
      // 表单
      form: {
        deviceRespList: []
      },
      // 除蓝牙设备
      types: [2, 4],
      // 生效期内禁止修改活动设备
      disabledActivity: this.$route.query.activityState == 0 ? true : false,
      // 生效期内领取数量禁止下调
      num: [],
      // 只读
      disabled: Boolean(this.$route.query.boolean),
      // 校验
      rules: {
        pic: [{
          required: true, message: '请上传活动图片', trigger: 'change'
        }],
        timeList: [{
          required: true, message: '请选择有效时间', trigger: 'change'
        }],
        deviceRespList: [{
          type: 'array', required: true, message: '请添加活动设备', trigger: 'change'
        }]
      }
    }
  },
  watch: {
    'form.deviceRespList': {
      handler(val) {
        for (let i in this.devOptions) {
          this.devOptions[i].disabled = false
        }
        // 禁用已关联设备
        val.map((i, index) => {
          if (i.deviceId) {
            let index = this.devOptions.findIndex(j => j.value === i.deviceId)
            this.devOptions[index].disabled = true
          }
        })
      },
      deep: true
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.getDetail()
    }
  },
  methods: {
    // 详情
    getDetail() {
      detail(this.$route.query.id).then(res => {
        if (res.code === 0) {
          this.form = res.data
          res.data.deviceRespList.map(i => {
            this.num.push(i.totalNum)
          })
        }
      })
    },

    // 上传图片
    upload(e) {
      this.form.pic = e.file
    },

    // 添加
    handlePush() {
      this.form.deviceRespList.push({})
    },

    // 已生效的活动 设备数量不能修改的比之前小
    handleChange(e, index) {
      if (this.disabledActivity && this.num[index] > e) {
        this.$message.error('已生效活动，当前领取数量不可减少')
      }
    },

    // 删除
    getDelete(deviceId, index) {
      this.form.deviceRespList.splice(index, 1)
      this.devOptions.map(i => {
        if (i.value === deviceId) {
          i.disabled = false
        }
      })
    },

    // 取消
    cancel() {
      this.$tab.closeOpenPage('/operation/activity')
    },

    // 确定
    getSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          submit(this.form).then(res => {
            if (res.code === 0) {
              this.$message.success('提交成功！')
              this.cancel()
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

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

.el-table__row {
  .el-form-item {
    width: 100%;
  }
}
</style>