<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>
            <span slot="label"><span class="required">*</span> 经营区域</span>
            <el-radio-group v-model="form.scope" @change="passValue">
              <el-radio :label="0" v-if="shopInfo.scope == 0">全国</el-radio>
              <el-radio :label="1" v-if="shopInfo.scope == 1">同城</el-radio>
              <el-radio :label="2" v-if="shopInfo.scope == 1">特价</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
      <el-col :span="24">
        <el-form-item prop="saleType">
          <span slot="label">销售方式</span>
          <el-radio-group v-model="form.saleType" @change="passValue">
            <el-radio
              :label="0"
              :value="0"
              v-if="shopInfo.scope == 0 || shopInfo.scope == 1"
              >{{
                shopInfo.scope == 0 ? "整车" : shopInfo.scope == 1 ? "普通商品" : ""
              }}</el-radio
            >
            <el-radio :label="2" :value="2" v-if="shopInfo.scope == 0">拼车</el-radio>
            <!-- <el-radio :label="3">预售</el-radio> -->
            <el-radio :label="4" :value="4" v-if="shopInfo.scope == 1">礼包</el-radio>
            <!-- <el-radio :label="1" :value="1" v-if="shopInfo.scope == 1">一键代发</el-radio> -->
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="shopInfo.scope == 0 && form.saleType == 0">
        <el-form-item prop="saleModel">
          <span slot="label">销售模式</span>
          <el-radio-group v-model="form.saleModel" @change="passValue">
            <el-radio :label="1">现货</el-radio>
            <el-radio :label="2" v-if="shopInfo.scope == 0">预售</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="form.saleModel == 2">
        <el-form-item prop="datePicker">
          <span slot="label">预售时间</span>
          <el-date-picker
            v-model="datePicker"
            type="datetimerange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="picker"
          >
          </el-date-picker>
        </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" v-if="form.saleType == 2">
        <el-form-item prop="carpoolSuccessTime">
          <span slot="label">拼车成功时间</span>
          <el-input
            v-model="form.carpoolSuccessTime"
            placeholder="请输入拼车成功时间"
            clearable
            style="width: 260px"
            @input="passValue"
          >
            <template slot="suffix"> 天 </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="form.saleType == 4">
        <el-form-item prop="giftDesc">
          <span slot="label">礼包描述</span>
          <el-input
            @input="passValue"
            v-model="form.giftDesc"
            maxlength="70"
            show-word-limit
            placeholder="请输入礼包描述"
            clearable
            style="width: 600px"
          >
          </el-input>
        </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内,至多可上传10张,第一张图默认为商品封面图</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" style="width: 70px; height: 70px" />
              </div>
            </draggable>
            <!-- <div class="fmt" v-if="index == 0">封面图</div>
                <img :src="item.url" style="width: 70px; height: 75px" /> -->
            <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";
export default {
  props: ["data"],
  components: { draggable },
  data() {
    return {
      form: {
        carpoolSuccessTime: "",
        scope: "",
        saleType: undefined,
        saleModel: undefined,
        categoryId: "",
        title: "",
        giftDesc: "",
        vid: "",
        bannerList: [],
        pic: "",
        categoryName: "",
        categoryIds: [],
        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" },
        ],
      },
      index: 0,
      shopInfo: {},
      datePicker: [],
      categoryName: "",
    };
  },
  watch: {
    //监听info对象
    data: {
      handler(newVal, oldVal) {
        //监听info对象变化
        if (newVal) {
          for (const key in this.form) {
            this.form[key] = newVal[key];
          }
          this.bannerList = [];
          this.form.bannerList = [];
          this.datePicker = [newVal.presaleStartTime, newVal.presaleEndTime];
          if (this.form.bannerList?.length > 0) {
            this.form.bannerList.forEach((e) => {
              this.bannerList.push({
                url: e.fileUrl,
              });
            });
          }
          if (this.form.pic) {
            this.bannerList.unshift({
              url: this.form.pic,
            });
          }
          this.categoryName = this.form.categoryName;
          console.log("111", this.form);
        }
      },
      deep: true, //深度监听
      immediate: true,
    },
  },

  created() {
    this.getInfo();
  },

  methods: {
    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) => {
          console.log(valid);
          if (valid) {
            resolve(valid);
          } else {
            resolve(valid);
          }
        });
      });
    },

    removeImg(index) {
      this.bannerList.splice(index, 1);
      this.passValue();
    },
    picker() {
      this.form.presaleStartTime = this.datePicker[0];
      this.form.presaleEndTime = this.datePicker[1];
      this.passValue();
    },
    getInfo() {
      getStoreInfo().then((res) => {
        if (res.code == 200) {
          this.shopInfo = res.data;
          this.form.scope = res.data.scope;
        }
      });
    },
    draggableChange() {
      this.passValue();
    },

    passValue() {
      this.form.bannerList = [];

      for (let index = 0; index < this.bannerList.length; index++) {
        this.form.bannerList.push({
          fileUrl: this.bannerList[index].url,
          sort: this.bannerList[index].name,
        });
      }
      if (this.bannerList.length > 1) {
        this.form.pic = this.bannerList[0].url;
      }
      if (this.form.scope == 1) {
        this.form.saleType = 0;
        this.form.saleModel = 1;
      }

      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) {
      let nodes = this.$refs.formCascader.getCheckedNodes();
      this.form.categoryName = nodes[0].label;
      // this.form.categoryIds = val;
      let list = [];
      val.forEach((e) => {
        list.push(parseInt(e));
      });
      this.form.categoryIds = JSON.stringify(list);
      if (val.length == 1) {
        this.form.categoryId = val[0];
      } else if (val.length == 2) {
        this.form.categoryId = val[1];
      } else if (val.length == 3) {
        this.form.categoryId = val[2];
      }
      this.passValue();
    },
    categoryLazyLoad(node, resolve) {
      let that = this;
      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;
}
.gb {
  position: absolute;
  left: 59px;
  top: -8px;
  cursor: pointer;
}
.fmt {
  position: absolute;
  width: 70px;
  height: 20px;
  background: #0000003d;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  color: #fff;
  bottom: 10px;
}
</style>
