<template>
  <el-form
    :model="form"
    ref="queryForm"
    size="small"
    :inline="true"
    label-width="120px"
    :rules="rules"
  >
    <el-row>
      <el-col :span="24">
        <el-form-item prop="saleType">
          <span slot="label">销售方式</span>
          <el-radio-group
            v-model="form.saleModel"
            @change="passValue"
            :disabled="actionType == 'edit'"
          >
            <el-radio :label="1" :value="1">普通商品</el-radio>
            <el-radio :label="5" :value="5">新人福利</el-radio>
            <el-radio :label="3" :value="3">团购秒杀</el-radio>
            <el-radio :label="4" :value="4">特价</el-radio>
            <el-radio :label="2" :value="2">预售</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="categoryId">
          <span slot="label">商品分类</span>
          <el-cascader
            v-model="form.categoryId"
            ref="formCascader"
            :placeholder="categoryName ? categoryName : '请选择分类'"
            :props="categoryprops"
            @change="cascaderChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="title">
          <span slot="label">商品名称</span>
          <el-input
            v-model="form.title"
            placeholder="请输入商品名称"
            clearable
            style="width: 260px"
            maxlength="20"
            show-word-limit
            @input="passValue"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="商品视频">
          <span class="tips">上传视频用户看的更直接</span>
          <el-upload
            list-type="picture-card"
            :show-file-list="false"
            :http-request="(data) => requestUpload(data, 'video')"
            :limit="1"
            action="#"
            accept=".mp4"
            ref="files"
          >
            <video
              v-if="form.vid"
              controls
              :src="form.vid"
              style="width: 80px; height: 80px"
            ></video>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="bannerList">
          <span slot="label">商品图</span>
          <span class="tips"
            >图片要求:大小3M内,至多可上传11张,第一张图默认为商品封面图</span
          >
          <div style="display: flex; flex-direction: row; align-items: center">
            <draggable
              style="display: flex; flex-direction: row; align-items: center"
              v-model="bannerList"
              group="people"
              @change="draggableChange"
              @start="start"
              @end="end"
            >
              <div class="item" v-for="(item, index) in this.bannerList" :key="index">
                <div class="fmt" v-if="index == 0">封面图</div>
                <div class="gb" @click="removeImg(index)">X</div>
                <img
                  :src="item.url || item.fileUrl"
                  style="width: 70px; height: 70px; border-radius: 10px"
                />
              </div>
            </draggable>

            <el-upload
              list-type="picture-card"
              :file-list="bannerList"
              :before-remove="requestRemove"
              :http-request="(data) => requestUpload(data, 'banner')"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :limit="11"
              action="#"
              :multiple="true"
              accept=".png,.jpg,.jpeg"
              ref="files"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import draggable from "vuedraggable";
import { getStoreInfo } from "@/api/common/index";
import { getClassificationListPage } from "@/api/common/index.js";
import { getToken } from "@/utils/auth";
import axios from "axios";
import moment from "moment";
export default {
  props: ["data"],
  components: { draggable },
  data() {
    return {
      form: {
        carpoolSuccessTime: "",
        scope: 3,
        saleType: 0,
        saleModel: 1,
        categoryId: "",
        title: "",
        giftDesc: "",
        vid: "",
        bannerList: [],
        pic: "",
        categoryName: "",
        categoryIds: [],
        datePicker: [],
        presaleStartTime: "",
        presaleEndTime: "",
      },
      bannerList: [],
      headers: { Auth: "Bearer " + getToken(), "Content-type": "multipart/form-data" },
      categoryprops: {
        checkStrictly: true,
        lazy: true,
        lazyLoad: this.categoryLazyLoad,
        label: "label",
        value: "value",
      },
      rules: {
        saleType: [{ required: true, message: "销售方式不能为空", trigger: "blur" }],
        saleModel: [{ required: true, message: "销售方式不能为空", trigger: "blur" }],
        categoryId: [{ required: true, message: "分类不能为空", trigger: "blur" }],
        title: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        giftDesc: [{ required: true, message: "礼包描述不能为空", trigger: "blur" }],
        bannerList: [
          { required: true, message: "商品图最低上传两张图片", trigger: "blur" },
        ],
        carpoolSuccessTime: [
          { required: true, message: "拼车成功时间不能为空", trigger: "blur" },
        ],
        datePicker: [{ required: true, message: "预售时间不能为空", trigger: "blur" }],
      },
      index: 0,
      shopInfo: {},
      categoryName: "",
      radio: "",
      actionType: "",
    };
  },
  created() {
    this.getInfo();
  },

  methods: {
    getFormInfo(record, type) {
      if (type != "cg") {
        this.actionType = "edit";
      } else {
        this.actionType = "";
      }

      this.form.datePicker = [];
      this.form.categoryId = record.categoryId;
      this.form.categoryIds = record.categoryIds;
      this.form.carpoolSuccessTime = record.carpoolSuccessTime;
      this.form.scope = record.scope;
      this.form.saleType = record.saleType;
      this.form.saleModel = record.saleModel;
      this.form.title = record.title;
      this.form.giftDesc = record.giftDesc;
      this.form.vid = record.vid;
      this.form.bannerList = record.bannerList;
      this.form.pic = record.pic;
      this.form.categoryName = record.categoryName;
      this.categoryName = record.categoryName;
      this.bannerList = [];
      if (this.form.bannerList?.length > 0) {
        this.bannerList = this.form.bannerList;
      }
      if (this.form.pic) {
        this.bannerList.unshift({
          fileUrl: record.pic,
          sort: 1,
        });
      }
      this.$forceUpdate();
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png" || "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG或PNG或JPEG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    formvalidate() {
      let that = this;
      return new Promise((resolve) => {
        that.$refs.queryForm.validate((valid, row) => {
          if (valid) {
            resolve(valid);
          } else {
            for (const key in row) {
              for (let index = 0; index < row[key].length; index++) {
                this.$message.error(row[key][index].message);
                return;
              }
            }
            resolve(valid);
          }
        });
      });
    },

    removeImg(index) {
      this.bannerList.splice(index, 1);
      this.passValue();
    },
    getInfo() {
      getStoreInfo().then((res) => {
        if (res.code == 200) {
          this.shopInfo = res.data;
          // this.form.scope = res.data.scope;
          // if (res.data.scope == 1) {
          this.form.saleType = 0;
          // this.form.saleModel = 1;
          // }
        }
      });
    },
    draggableChange() {
      this.passValue();
    },

    passValue() {
      this.form.bannerList = [];
      if (this.bannerList.length > 0) {
        console.log("bannerList", this.bannerList);
        for (let index = 0; index < this.bannerList.length; index++) {
          this.form.bannerList.push({
            fileUrl: this.bannerList[index].url || this.bannerList[index].fileUrl,
            sort: this.bannerList[index].name,
          });
        }
        this.form.pic = this.bannerList[0].url || this.bannerList[0].fileUrl;
        if (this.form.pic) {
          this.form.bannerList.shift();
        }
      } else {
        this.form.pic = "";
      }
      this.$emit("updateValue", this.form);
    },

    requestRemove(val, list, index) {
      this.bannerList.forEach((e, index) => {
        if (e.uid == val.uid) {
          this.bannerList.splice(index, 1);
        }
      });
      this.passValue();
    },
    cascaderChange(val) {
      this.$nextTick(() => {
        const dom = document.getElementsByClassName("el-radio is-checked");
        //这里我把dom打出来看了 最后一个选项才是我选中的节点 即[length-1] 有的博主写的是 第一个元素 即[0] 大家自行尝试
        let radioDom = dom[dom.length - 1];
        const brother = radioDom.nextElementSibling;
        brother.click();
        let nodes = this.$refs.formCascader.getCheckedNodes();
        this.form.categoryName = nodes[0].label;
        this.form.categoryIds = val;
        this.form.categoryIds = JSON.stringify(this.form.categoryIds);
        this.passValue();
      });
    },
    categoryLazyLoad(node, resolve) {
      let level = node.level;
      if (!node.data) {
        getClassificationListPage({ parentId: 0 }).then((res) => {
          //接口
          const nodes = Array.from(res.data).map((item, index) => ({
            value: item.id,
            label: `${item.className}`,
            leaf: level >= 2,
          }));
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else if (level == 1) {
        getClassificationListPage({ parentId: node.data.value }).then((res) => {
          const nodes = Array.from(res.data).map((item) => ({
            value: item.id,
            label: `${item.className}`,
            leaf: level >= 2,
            // level: 2,
          }));
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else if (level == 2) {
        getClassificationListPage({ parentId: node.data.value }).then((res) => {
          const nodes = Array.from(res.data).map((item) => ({
            value: item.id,
            label: `${item.className}`,
            leaf: level >= 1,
            level: 1,
          }));
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes);
        });
      } else {
        resolve({});
      }
    },

    // 可以获取图片参数
    async requestUpload(data, type) {
      const formdata = new FormData();
      formdata.append("file", data.file);
      const res = await axios.post(
        `${process.env.VUE_APP_NSY_UPLOAD_API}/api/third/op/v1/third/uploadPic`,
        formdata,
        {
          headers: this.headers,
        }
      );
      if (res.data.data) {
        if (type == "video") {
          this.form.vid = res.data.data;
        } else if (type == "banner") {
          this.bannerList.push({
            name: this.index,
            url: res.data.data,
          });
          this.index++;
        }
        this.passValue();
        this.$forceUpdate();
      }
    },
  },
};
</script>

<style>
.el-cascader-panel
  > .el-scrollbar:first-child
  > .el-cascader-menu__wrap
  > .el-cascader-menu__list
  > .el-cascader-node
  > .el-radio {
  display: none;
}
/* .el-cascader-menu__wrap > .el-cascader-menu__list > .el-cascader-node > .el-radio {
    display: none;
  } */
</style>

<style scoped>
.item {
  position: relative;
  margin-right: 10px;
}
.gb {
  position: absolute;
  left: 59px;
  top: -8px;
  cursor: pointer;
}
.fmt {
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  position: absolute;
  width: 70px;
  height: 20px;
  background: #0000003d;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  color: #fff;
  bottom: 10px;
}
</style>
