<template>
  <el-dialog :visible.sync="visible" v-bind="modalOptions">
    <el-form
      ref="formData"
      :model="formData"
      :rules="formRules"
      size="mini"
      label-suffix=":"
      label-width="150px"
    >
      <h2>基础信息</h2>
      <el-form-item label="活动名称" prop="composeName">
        <el-input
          v-model="formData.composeName"
          maxlength="20"
          placeholder="请输入活动名称"
          :disabled="formData.state === 0"
        />
      </el-form-item>
      <el-form-item label="请选择区域" prop="regionId">
        <el-cascader
          v-model="regionArrDialog"
          :props="regionProps"
          size="large"
          placeholder="请选择区域"
          @change="
            formData.regionId = [
              ...new Set(regionArrDialog.map((i) => i[i.length - 1])),
            ].join(',')
          "
        ></el-cascader>
        <div v-if="String(formData.regionId)">
          已选ID：{{ formData.regionId }}
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          maxlength="255"
          type="textarea"
          placeholder="请输入活动介绍"
          :disabled="formData.state === 0"
          style="width: 400px"
        />
      </el-form-item>
      <el-form-item label="报名时间" prop="dateTime1">
        <el-date-picker
          v-model="formData.dateTime1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="formData.state === 3 || formData.state === 4"
        />
        <p class="timeInfo">报名时间不能交叉且报名时间不能大于活动时间</p>
      </el-form-item>
      <el-form-item label="活动时间" prop="dateTime2">
        <el-date-picker
          v-model="formData.dateTime2"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="formData.state === 3 || formData.state === 4"
        />
        <p class="timeInfo">平台活动时间不能交叉并且活动时间不能小于报名时间</p>
      </el-form-item>
      <el-form-item label="活动保证金">
        <el-radio-group v-model="formData.ifBond">
          <el-radio :label="1" :disabled="formData.state === 0">需要</el-radio>
          <el-radio :label="0" :disabled="formData.state === 0"
            >不需要</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.ifBond === 1" label="保证金金额">
        <el-input
          v-model="formData.bondMoney"
          maxlength="9"
          placeholder="请输入活动保证金金额"
          :disabled="formData.state === 0"
        />
      </el-form-item>
      <h2>优惠规则</h2>
      <el-form-item label="是否限购">
        <el-radio-group v-model="formData.ifLimit">
          <el-radio :label="2" :disabled="formData.state === 0">限购</el-radio>
          <el-radio :label="1" :disabled="formData.state === 0"
            >不限购</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.ifLimit === 2" label="限购(件/人)">
        <el-input
          v-model="formData.limitNumber"
          maxlength="9"
          placeholder="请输入限购数量"
          :disabled="formData.state === 0"
        />
      </el-form-item>
      <el-form-item label="优惠券叠加">
        <el-radio-group v-model="formData.ifAdd">
          <el-radio :label="1" :disabled="formData.state === 0">叠加</el-radio>
          <el-radio :label="0" :disabled="formData.state === 0"
            >不叠加</el-radio
          >
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {
  getPlatformComposeById,
  savePlatformComposeActivity,
  updatePlatformComposeActivity,
} from "@/api/active/combinationActivities";
import { getProvinceList, getChildAreaList } from "@/api/address";

export default {
  name: "EditModal",
  components: {},
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: "820px",
        title: "",
      },
      visible: false,
      formData: {
        dateTime1: [], // 后端不接收
        dateTime2: [], // 后端不接收
        composeId: "",
        regionId: "",
        composeName: "",
        remark: "",
        signStartTime: "",
        signEndTime: "",
        startTime: "",
        endTime: "",
        ifLimit: "",
        limitNumber: "",
        ifAdd: "",
        state: "",
        ifBond: "", // 活动保证金
        bondMoney: "", // 保证金金额
        shops: null,
        products: null,
      },
      formRules: {
        remark: [{ max: 255, message: "长度在 255 个字符内", trigger: "blur" }],
        composeName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        regionId: [{ required: true, message: "请选择地址", trigger: "blur" }],
        dateTime1: [
          { type: "array", required: true, message: "请选择报名时间" },
        ],
        dateTime2: [
          { type: "array", required: true, message: "请选择活动时间" },
        ],
        bondMoney: [],
      },
      regionArrDialog: [],
      regionProps: {
        checkStrictly: true,
        multiple: true,
        lazy: true,
        label: "name",
        value: "id",
        lazyLoad(node, resolve) {
          const { level, value } = node;
          if (level === 0) {
            resolve([
              {
                id: 0,
                parentId: 0,
                name: "全中国",
                shortName: "全国",
                longitude: "108.55",
                latitude: "34.32",
                level: 1,
                sort: 1,
                status: true,
              },
            ]);
          } else if (level === 1) {
            getProvinceList().then((res) => {
              resolve(res.data);
            });
          } else if (level != 0 && level != 1) {
            getChildAreaList(value).then((res) => {
              resolve(
                res.data.map((item) => {
                  item.leaf = level === 4;
                  return item;
                })
              );
            });
          }
        },
      },
    };
  },
  watch: {
    "formData.ifBond": {
      deep: true,
      handler(val) {
        if (val) {
          this.formRules.bondMoney = [
            { required: true, message: "请输入金额", trigger: "blur" },
            {
              pattern: /^0\.\d{0,2}$|^[1-9]\d*\.\d{0,2}$|^[1-9]\d*$/,
              message: "数值有误",
            },
          ];
        } else {
          this.formRules.bondMoney = [];
        }
      },
    },
  },
  methods: {
    //  分享规则切换
    shareRuleChange(){
      this.formData.shareMoney = 0
    },
    handleClose() {
      this.visible = false;
    },
    async initList() {},
    handleOpen(params = {}) {
      this.modalOptions.title = params.composeId
        ? "编辑组合活动"
        : "添加组合活动";
      this.formData = Object.assign(this.$options.data().formData, params, {
        dateTime1: params.signTime ? params.signTime.split("~") : "",
        dateTime2: params.time ? params.time.split("~") : "",
      });
      if (this.formData.regionId)
        this.regionArrDialog = this.formData.regionId
          .split(",")
          .map((i) => [i]);
      this.visible = true;
      this.initList();
      if (params.composeId) {
        this.getInfo(params.composeId);
      } else {
        this.$refs.formData && this.$refs.formData.resetFields();
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: "加载中" });
      try {
        const res = await getPlatformComposeById({ id });
        this.formData = Object.assign(
          this.$options.data().formData,
          res.data,
          {
            composeId: res.data.composeId || "",
            composeName: res.data.composeName || "",
            remark: res.data.remark || "",
            signStartTime: res.data.signStartTime || "",
            signEndTime: res.data.signEndTime || "",
            startTime: res.data.startTime || "",
            endTime: res.data.endTime || "",
            ifLimit: res.data.ifLimit || "",
            limitNumber: res.data.limitNumber || "",
            ifAdd: res.data.ifAdd,
            state: res.data.state,
            ifBond: res.data.ifBond,
            bondMoney: res.data.bondMoney || "",
            shops: res.data.shops || null,
            products: res.data.products || null,
          },
          {
            dateTime1:
              res.data.signStartTime || res.data.signEndTime
                ? [res.data.signStartTime, res.data.signEndTime]
                : "",
            dateTime2:
              res.data.startTime || res.data.endTime
                ? [res.data.startTime, res.data.endTime]
                : "",
          }
        );
        if (this.formData.regionId)
          this.regionArrDialog = this.formData.regionId
            .split(",")
            .map((i) => [i]);
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate();
        });
      } finally {
        loading.close();
      }
    },
    handleSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: "加载中" });
          try {
            const { dateTime1, dateTime2, ...otps } = this.formData;
            const params = {
              ...otps,
              signStartTime: dateTime1 && dateTime1[0],
              signEndTime: dateTime1 && dateTime1[1],
              startTime: dateTime2 && dateTime2[0],
              endTime: dateTime2 && dateTime2[1],
            };
            let errMsg = "";
            if (params.composeName === "") {
              errMsg += " 活动名称 ";
            }
            if (params.signStartTime === "" || params.signEndTime === "") {
              errMsg += " 报名时间 ";
            }
            if (params.startTime === "" || params.endTime === "") {
              errMsg += " 活动时间 ";
            }
            if (errMsg.length !== 0) {
              this.$message.error(`请输入${errMsg}`);
              return;
            }
            this.formData.composeId
              ? await updatePlatformComposeActivity(params)
              : await savePlatformComposeActivity(params);
            loading.close();
            this.$message({
              message: `${this.formData.composeId ? "编辑" : "添加"}成功!`,
              type: "success",
            });
            this.$emit("success");
            this.visible = false;
          } catch (e) {
            loading.close();
          } finally {
            loading.close();
          }
        } else {
          this.$message({ message: "请输入相关信息", type: "warning" });
          return false;
        }
      });
    },
  },
};
</script>
