<!-- 活动管理 详情 -->
<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="活动类型：">
        <el-select
          v-model="form.platformName"
          placeholder="请选择活动类型"
          :disabled="disabledActivity"
        >
          <el-option
            v-for="item in platformNames"
            :key="item"
            :value="item"
            :label="item"
          />
        </el-select>
      </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
            v-if="form.platformName === platformNames[1]"
            label="活动权益"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="`deviceRespList.${scope.$index}.goodId`"
                :rules="{ required: true, trigger: 'change' }"
              >
                <el-select
                  v-model="scope.row.goodId"
                  placeholder="请选择活动权益"
                  :disabled="scope.row.deviceId == null || disabledActivity"
                >
                  <el-option
                    v-for="item in form.platformName === platformNames[1]?aaaa[scope.row.deviceId]:serviceTimeOptions"
                    :key="item.goodId"
                    :value="item.goodId"
                    :label="item.goodName"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->

          <el-table-column label="活动权益" align="center">
            <template slot-scope="scope">
              <el-form-item>
                <el-select
                  v-model="scope.row.goodId"
                  placeholder="请选择活动权益"
                  :disabled="disabledActivity"
                >
                  <el-option
                    v-for="item in form.platformName === platformNames[1]
                      ? aaaa[scope.row.deviceId]
                      : serviceTimeOptions"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              {{ scope.row.deviceId }}---{{ aaaa }}--
            </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, goodList, submit } from "@/api/operation/activity";
import { devMixin, serviceTimeMixin } from "@/mixin/index";
export default {
  mixins: [serviceTimeMixin, devMixin],

  data() {
    return {
      aaaa: {},
      // 表单
      deviceRespListTemp: [],
      form: {
        deviceRespList: [],
      },

      platformNames: ["会员赠送", "流量赠送"],
      // 除蓝牙设备
      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) {
        if (this.form.platformName == this.platformNames[1]) {
          if (this.deviceRespListTemp.length == val.length) {
            for (var i = 0; i < val.length; i++) {
              var deviceId = val[i].deviceId;
              if (this.deviceRespListTemp[i].deviceId != val[i].deviceId) {
                let a = this.aaaa[`${deviceId}`];
                if (a == null || a.length == 0) {
                  this.getGoodList(deviceId);
                }
                break;
              }
            }
          }
        }
        this.deviceRespListTemp = JSON.parse(JSON.stringify(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,
    },

    "form.platformName": {
      handler(val) {
        for (let i in this.form.deviceRespList) {
          if (this.form.deviceRespList[i].goodId != null) {
            this.form.deviceRespList[i].goodId = null;
          }
        }
      },
      deep: true,
    },

    // "form.platformName": {
    //   handler(val) {
    //     console.log("gasdfasdfasdfaf==22==" + this.form.platformName);
    //   },
    //   deep: true,
    // },
  },
  mounted() {
    this.getDevList();
    if (this.$route.query.id) {
      this.getDetail();
    }
  },

  methods: {
    // 超级详情
    getGoodList(deviceId) {
      let platformId = 1;
      let param = {
        deviceId: deviceId,
        platformId: platformId,
      };

      goodList(param).then((res) => {
        if (res.code === 0) {
          this.aaaa[`${deviceId}`] = res.data;
          console.log(
            "gasdfasdfasdfaf==啊啊啊啊=11=" + JSON.stringify(this.aaaa)
          );
          ///goodId  goodName
        }
      });
    },

    // 详情
    getDetail() {
      detail(this.$route.query.id).then((res) => {
        if (res.code === 0) {
          res.data.platformName =
            res.data.platformId === 1
              ? this.platformNames[1]
              : this.platformNames[0];
          this.form = res.data;
          res.data.deviceRespList.map((i) => {
            this.num.push(i.totalNum);
          });
        }
      });
    },

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

    // 添加
    handlePush() {
      if (this.form.platformName != null) {
        this.form.deviceRespList.push({});
      } else {
        this.$message.success("请先选择活动类型");
      }
    },

    // 已生效的活动 设备数量不能修改的比之前小
    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>