<template>
  <div class="app-main-height">
    <el-tabs v-model="activeName" @tab-click="handleClick(activeName)">
      <el-tab-pane label="商品信息" name="first">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="20" :lg="25" :xl="8">
            <el-form
              ref="addGoods"
              :model="addGoods"
              label-width="100px"
              class="demo-ruleForm"
              :rules="rules"
            >
              <el-form-item label="选择分类" prop="classificationID">
                <GoodsClassification
                  :classificationid="addGoods.classificationID"
                  @choseGoodsType="choseGoodsType"
                />
              </el-form-item>
              <el-form-item label="商品名称" prop="goodsName">
                <el-input
                  v-model.trim="addGoods.goodsName"
                  placeholder="请输入商品名称"
                />
              </el-form-item>

              <el-form-item label="选择产地" prop="addr">
                <v-distpicker
                  ref="getprovince"
                  :provinceid.sync="addGoods.provinceID"
                  :cityid.sync="addGoods.cityID"
                  :countyid.sync="addGoods.countyID"
                  @getAreaCode="getAreaCode"
                />
              </el-form-item>
              <el-form-item label="供应商名称">
                <el-input
                  v-model="addGoods.providerName"
                  placeholder="请输入供应商名称"
                />
              </el-form-item>
              <el-form-item label="商品销量" prop="sales">
                <el-input
                  v-model.number="addGoods.sales"
                  placeholder="请输入商品销量,不填写则使用真实销量做展示"
                />
              </el-form-item>
              <el-form-item label="商品简介" prop="goodsOverview">
                <el-input
                  v-model="addGoods.goodsOverview"
                  type="textarea"
                  placeholder="简介"
                />
              </el-form-item>
              <el-form-item label="包邮说明">
                <el-input
                  v-model="addGoods.mailInstruction"
                  type="textarea"
                  placeholder="说明"
                />
              </el-form-item>
              <el-form-item label="商品主图" prop="images">
                <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :http-request="request"
                  :file-list="addGoods.images"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :limit="5"
                  :on-exceed="handleExceed"
                  accept=".jpg, .jpeg, .png"
                  id="items"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <!-- <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="beforeUpload"
                  :file-list="addGoods.images"
                  :on-remove="handleRemove"
                  :limit="5"
                  :on-exceed="handleExceed"
                  accept=".jpg, .jpeg, .png"
                  id="items"
                >
                  <i class="el-icon-plus" />
                </el-upload> -->
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <P class="text"
                  >请保证图片尺寸为328*328,格式为jpg / jpeg / png的图片</P
                >
              </el-form-item>
              <el-form-item label="视频区">
                <div class="imgFile">
                  <el-button type="primary" size="mini"> 上传视频 </el-button>
                  <input
                    id="imgFile"
                    class="upload_input"
                    type="file"
                    accept="video/*"
                    @change="changeVideo($event)"
                  />
                </div>
                <video
                  v-if="videoUrl != ''"
                  :src="videoUrl"
                  controls="controls"
                  width="500"
                  height="400"
                />
                <el-button
                  v-if="videoUrl != ''"
                  type="text"
                  @click="handleUpdatevideo"
                  >删除</el-button
                >
                <p class="text">请保证视频格式正确，且不超过10M</p>
              </el-form-item>
              <el-form-item label="商品详情">
                <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :http-request="request1"
                  :on-success="handleSuccess1"
                  :on-remove="handleRemove1"
                  :file-list="addGoods.goodsDetaisImages"
                  :multiple="true"
                  accept=".jpg, .jpeg, .png"
                  id="items1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <!-- <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="beforeUpload1"
                  :file-list="addGoods.goodsDetaisImages"
                  :on-remove="handleRemove1"
                  :multiple="true"
                  id="items1"
                  accept=".jpg, .jpeg, .png"
                >
                  <i class="el-icon-plus" />
                </el-upload> -->
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <P class="text"
                  >请保证图片尺寸为328*328,格式为jpg / jpeg / png的图片</P
                >
              </el-form-item>
              <el-form-item>
                <el-button
                  :loading="loading"
                  type="primary"
                  @click.native.prevent="
                    $route.query.name === 'create'
                      ? submitForm('addGoods')
                      : editGoods('addGoods')
                  "
                >
                  保存并下一步
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="价格库存" name="second" :disabled="tabpane">
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="small"
          style="margin: 20px 0"
          @click="handleCreate"
        >
          新增套餐
        </el-button>
        <el-table :data="tableData">
          <template slot="empty">
            <p>{{ dataText }}</p>
          </template>
          <el-table-column prop="comboGoodsName" label="套餐名称" />
          <el-table-column prop="comboGoodsNum" label="库存" />

          <el-table-column prop="comboGoodsPrice" label="单价" />
          <el-table-column prop="comboCostPrice" label="成本价" />

          <el-table-column label="操作">
            <template slot-scope="{ row, $index }">
              <el-button type="text" @click="handleUpdate(row)">编辑</el-button>
              <el-button type="text" @click="handleDelete(row, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button
          v-if="tableData.length > 0"
          type="primary"
          size="small"
          style="margin: 20px 0"
          @click="handlegoodsSubmit"
        >
          提交审核
        </el-button>
      </el-tab-pane>
    </el-tabs>
    <newpackage
      ref="newpackage"
      :dialogstatus="dialogstatus"
      @fetchData="getList"
    />
  </div>
</template>

<script>
import VDistpicker from "../../components/distpicker";
import newpackage from "./components/newpackage";
import GoodsClassification from "../../components/GoodsClassification";
import { mapGetters } from "vuex";
import Sortable from "sortablejs";
export default {
  name: "Form",
  components: { VDistpicker, newpackage, GoodsClassification },
  data() {
    const validategoodsName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入商品名称"));
      } else if (value.length > 40) {
        callback(new Error("商品名称长度不能超出40个字符"));
      } else {
        callback();
      }
    };
    const validateclassificationID = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择商品分类"));
      } else {
        callback();
      }
    };
    const validateaddr = (rule, value, callback) => {
      if (
        this.addGoods.provinceID === "" ||
        this.addGoods.cityID === ""
        // this.addGoods.countyID === ""
      ) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    const validategoodsOverview = (rule, value, callback) => {
      if (value.length > 40) {
        callback(new Error("商品简介长度不能超出40个字符"));
      } else {
        callback();
      }
    };
    const validateimages = (rule, value, callback) => {
      if (this.addGoods.images.length <= 0) {
        callback(new Error("请上传商品主图"));
      } else {
        callback();
      }
    };
    return {
      remakeID: "",
      remake: "",
      loading: false,
      activeName: "first",
      videoFlag: false,
      dialogstatus: "",
      isupload: false,
      dialogImageUrl: "",
      dialogVisible: false,
      tabpane: false,
      imgUrl: [],
      disabled: false,
      dataText: "暂无数据",
      videoUrl: "",
      images: [],
      addGoods: {
        classificationID: "",
        classificationName: "",
        provinceID: "",
        provinceName: "",
        cityID: "",
        cityName: "",
        countyID: "",
        countyName: "",
        goodsName: "",
        mailInstruction: "",
        goodsOverview: "",
        goodsDetais: "",
        video: "",
        images: [],
        goodsDetaisImages: [],
        providerName: "",
      },
      config2: {
        id: "mse2",
        url: "",
        volume: 1,
        autoplay: true,
      },
      Player2: null,
      config1: {
        id: "mse1",
        url: "",
        volume: 1,
        autoplay: false,
      },
      Player1: null,
      tableData: [],
      newList: [],
      temp: {
        goodsID: "",
        comboGoodsPrice: "",
        comboGoodsNum: "",
        comboGoodsName: "",
        comboGoodsID: "",
      },
      rules: {
        classificationID: [
          {
            required: true,
            trigger: "blur",
            validator: validateclassificationID,
          },
        ],
        addr: [{ required: true, trigger: "blur", validator: validateaddr }],
        goodsName: [
          { required: true, trigger: "blur", validator: validategoodsName },
        ],
        goodsOverview: [
          {
            required: false,
            trigger: "blur",
            validator: validategoodsOverview,
          },
        ],
        images: [
          { required: true, trigger: "blur", validator: validateimages },
        ],
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个活动性质",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["goodsID", "merchantsId", "goodstate"]),
  },
  created() {
    if (this.$route.query.name === "create") {
      this.tabpane = true;
    } else if (this.$route.query.name === "update") {
      this.tabpane = false;
      this.getGoodsDetails();
    }
    this.addGoods.providerName = sessionStorage.getItem("providerName");
  },
  methods: {
    // 商品主图切换位置
    setSort() {
      var el = document.getElementById("items").querySelectorAll(".el-upload-list--picture-card")[0];
      var sortable = Sortable.create(el, {
        onUpdate: (event) => {
          var newIndex = event.newIndex, //新的索引
            oldIndex = event.oldIndex; //旧的索引
          if (newIndex > oldIndex) {
            el.insertBefore(el.children[newIndex], el.children[oldIndex]);
          } else {
            el.insertBefore(
              el.children[newIndex],
              el.children[oldIndex].nextSibling
            );
          }
          //列表数组更新
          var item = this.addGoods.images.splice(oldIndex, 1);
          this.addGoods.images.splice(newIndex, 0, item[0]);
        },
      });
    },
    // 商品详情切换位置
    setSortgoodsDetais() {
      var el = document.getElementById("items1").querySelectorAll(".el-upload-list--picture-card")[0];
      var sortable = Sortable.create(el, {
        onUpdate: (event) => {
          var newIndex = event.newIndex, //新的索引
            oldIndex = event.oldIndex; //旧的索引
          if (newIndex > oldIndex) {
            el.insertBefore(el.children[newIndex], el.children[oldIndex]);
          } else {
            el.insertBefore(
              el.children[newIndex],
              el.children[oldIndex].nextSibling
            );
          }
          //列表数组更新
          var item = this.addGoods.goodsDetaisImages.splice(oldIndex, 1);
          this.addGoods.goodsDetaisImages.splice(newIndex, 0, item[0]);
        },
      });
    },
    // 商品主图
    // 上传成功定义addGoods.images
    handleSuccess(res, file, fileList) {
	    this.addGoods.images.push(file);
    },
    // 上传失败
    handleError(err, file, fileList){
      this.$message({
        message: "上传文件失败，请重新上传",
        type: "error",
      });
    },
    // http-request
    request(params){
      const file = params.file;
      const isLt50M = file.size / 1024 / 1024 < 2;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 2M!",
          type: "error",
        });
        return false;
      };
      const fd = new FormData();
      fd.append("file", file);
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        res.name = file.name;
        res.url = res.imgurl;
        params.onSuccess(res);
      }).catch((err)=>{
        params.onError(err);
      })
    },

    // 上传成功定义addGoods.images
    handleSuccess1(res, file, fileList) {
	    this.addGoods.goodsDetaisImages.push(file);
    },
    // http-request
    request1(params){
      const file = params.file;
      const isLt50M = file.size / 1024 / 1024 < 2;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 2M!",
          type: "error",
        });
        return false;
      };
      const fd = new FormData();
      fd.append("file", file);
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        res.name = file.name;
        res.url = res.imgurl;
        params.onSuccess(res);
      }).catch((err)=>{
        params.onError(err);
      })
    },
    //图片上传之前调用做一些拦截限制
    // beforeUpload(e) {
    //   const isLt50M = e.size / 1024 / 1024 < 2;
    //   if (!isLt50M) {
    //     this.$message({
    //       message: "上传文件大小不能超过 2M!",
    //       type: "error",
    //     });
    //     return false;
    //   }
    //   // const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
    //   const fd = new FormData();
    //   // fd.append("avatar_file", e);
    //   // fd.append("avatar_data", avatar_data);
    //   fd.append("file", e);
    //   this.$http.post(this.$api.uploadFile, fd).then((res) => {//https://81ronggui.oss-cn-beijing.aliyuncs.com
    //     // this.dialogImageUrl = `https://81ronggui.oss-cn-beijing.aliyuncs.com${res.url}`;
    //     res.name = e.name;
    //     res.url = res.imgurl; 
    //     this.addGoods.images.push(res);
    //     this.$nextTick(() => {
    //       this.setSort();
    //     });
    //   });
    // },
    // beforeUpload1(e) {
    //   const isLt50M = e.size / 1024 / 1024 < 2;
    //   if (!isLt50M) {
    //     this.$message({
    //       message: "上传文件大小不能超过 2M!",
    //       type: "error",
    //     });
    //     return false;
    //   }
    //   const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
    //   const fd = new FormData();
    //   // fd.append("avatar_file", e);
    //   // fd.append("avatar_data", avatar_data);
    //   fd.append("file", e);
    //   this.$http.post(this.$api.uploadFile, fd).then((res) => {
    //     res.name = e.name;
    //     res.url = res.imgurl;
    //     this.dialogImageUrl = res.url;
    //     // this.dialogImageUrl = `https://81ronggui.oss-cn-beijing.aliyuncs.com${res.url}`;
    //     this.addGoods.goodsDetaisImages.push(res);
    //     console.log(this.addGoods.goodsDetaisImages)
    //     this.$nextTick(() => {
    //       this.setSortgoodsDetais();
    //     });
    //   });
    // },
    // 保存并下一步
    submitForm(formName) {
      if (this.remake == "remake") {
        this.addGoods.goodsID = this.goodsID;
        this.editGoods("addGoods");
        return false;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.addGoods.merchantsID = this.merchantsId;
          const params = Object.assign(
            {},
            {
              type: "addGoods",
              data: this.addGoods,
            }
          );
          this.$store
            .dispatch("goods/addGoods", params)
            .then((response) => {
              this.activeName = "second";
              this.getComboList();
              this.remake = "remake";
              this.loading = false;
              this.tabpane = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName("is-error");
            isError[0].querySelector("input").focus();
          }, 100);
          this.loading = false;
          return false;
        }
      });
    },
    // 添加主推商品
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传5张`);
    },
    // 商品提交审核
    handlegoodsSubmit() {
      const params = {
        type: "goodsSubmit",
        data: {
          goodsID: this.goodsID,
        },
      };
      this.$http.post(this.$api.goodsSubmit, params).then((res) => {
        this.$router.push({ path: "/Commoditymanagement/Commoditylist" });
      });
    },
    // 获取商品详情
    async getGoodsDetails() {
      const params = {
        type: "getGoodsDetails",
        data: {
          goodsID: this.goodsID,
        },
      };
      await this.$http.post(this.$api.getGoodsDetails, params).then((res) => {
        this.addGoods = res;
        res.providerName == "" || !this.addGoods.providerName
          ? (this.addGoods.providerName =
              sessionStorage.getItem("providerName"))
          : res.providerName;
        //  console.log(this.addGoods);
        if (this.addGoods.images === "") {
          this.addGoods.images = [];
        } else {
          this.$nextTick(() => {
            this.setSort();
          });
        }
        if (this.addGoods.goodsDetaisImages === "") {
          this.addGoods.goodsDetaisImages = [];
        } else {
          this.$nextTick(() => {
            this.setSortgoodsDetais();
          });
        }
        if (res.video === "") {
          this.videoUrl = "";
          this.addGoods.video = "";
        } else {
          this.videoUrl = res.video.url;
          this.addGoods.video = res.video.imgurl;
        }
      });
    },
    // 上传视频
    changeVideo(e) {
      console.log(e);
      const current = e.target.files[0];
      if (!(current.size / 1024 / 1024 < 10)) {
        this.$message.error("上传视频大小不能超过10MB哦!");
      }
      const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
      const fd = new FormData();
      fd.append("avatar_file", current);
      fd.append("avatar_data", avatar_data);
      // fd.append("file", e);  uploadAvatar  uploadFile
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        this.addGoods.video = res.imgurl;
        this.videoUrl = res.url;
      });
    },
    // 头部选择
    handleClick(activeName) {
      if (this.activeName === "second") {
        this.getComboList();
      }
    },
    // 获取商品套餐列表
    getComboList() {
      const params = {
        type: "getComboList",
        data: {
          goodsID: this.goodsID,
        },
      };
      this.$http.post(this.$api.getComboList, params).then((res) => {
        if (res.combos.length > 0) {
          // console.log(res.combos);
          this.tableData = res.combos;
          this.remakeID;
        } else {
          this.tableData = [];
        }
      });
    },
    // 图片删除
    handleRemove(file, fileList) {
      if (this.addGoods.images.indexOf(file) > -1) {
        const index = this.addGoods.images.findIndex((item) => {
          return item.uid === file.uid;
        });
        this.addGoods.images.splice(index, 1);
      }
    },
    // 图片删除
    handleRemove1(file, fileList) {
      if (this.addGoods.goodsDetaisImages.indexOf(file) > -1) {
        const index = this.addGoods.goodsDetaisImages.findIndex((item) => {
          return item.uid === file.uid;
        });
        this.addGoods.goodsDetaisImages.splice(index, 1);
      }
    },
    handleDelete(row, index) {
      if (this.goodstate === "1" || this.goodstate === "0") {
        if (this.tableData.length <= 1) {
          this.$baseConfirm(
            "商品最后一个套餐被删除后，商品进入已下架状态，请确认是否继续操作!",
            null,
            async () => {
              this.delComboGoods(row, index);
            }
          );
        } else {
          this.$baseConfirm(
            "删除套餐后，该商品套餐将不在小程序显示。请确认是否继续操作!",
            null,
            async () => {
              this.delComboGoods(row, index);
            }
          );
        }
      } else {
        this.delComboGoods(row, index);
      }
    },
    // 删除商品套餐
    delComboGoods(row, index) {
      const params = {
        type: "delComboGoods",
        data: {
          comboGoodsID: row.comboGoodsID,
        },
      };
      this.$http.post(this.$api.delComboGoods, params).then((res) => {
        this.getComboList();
        this.$baseMessage("删除成功", "success");
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getList($event) {
      if (this.dialogstatus === "update") {
        this.getComboList();
      } else {
        this.getComboList();
      }
    },
    // 新增套餐
    handleCreate() {
      this.dialogstatus = "create";
      this.$nextTick(() => {
        this.$refs["newpackage"].showEdit();
      });
    },
    // 编辑套餐
    handleUpdate(row) {
      // console.log(row);
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogstatus = "update";
      // console.log(this.temp);
      this.$nextTick(() => {
        this.$refs["newpackage"].showEdit(this.temp);
      });
    },
    // 获取商品分类
    choseGoodsType(obj) {
      this.addGoods.classificationID = obj.goodsClassificationID;
      this.addGoods.classificationName = obj.goodsClassificationName;
    },
    // 视频删除
    handleUpdatevideo() {
      this.addGoods.video = "";
      this.videoUrl = "";
    },
    // 获取省市区
    getAreaCode(area) {
      console.log("area", area);
      switch (area.key) {
        case "city":
          this.addGoods.provinceID = area.obj.id;
          this.addGoods.provinceName = area.obj.name;
          break;
        case "street":
          this.addGoods.cityID = area.obj.id;
          this.addGoods.cityName = area.obj.name;
          break;
        case "village":
          this.addGoods.countyID = area.obj.id;
          this.addGoods.countyName = area.obj.name;
          break;
      }
    },
    // 编辑商品
    editGoods(formName) {
      this.addGoods.providerName == ""
        ? (this.addGoods.providerName = sessionStorage.getItem("providerName"))
        : true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.addGoods.merchantsID = this.merchantsId;
          const params = {
            type: "editGoods",
            data: this.addGoods,
          };
          if (this.goodstate === "1") {
            this.$baseConfirm(
              "商品信息修改，商品将下架，请重新提交审核!",
              null,
              async () => {
                this.$store
                  .dispatch("goods/editGoods", params)
                  .then((response) => {
                    this.activeName = "second";
                    this.getComboList();
                    this.loading = false;
                  });
              }
            );
            this.loading = false;
          } else if (this.goodstate === "0") {
            this.$baseConfirm(
              "商品信息修改，商品将下架，请重新提交审核!",
              null,
              async () => {
                this.$store
                  .dispatch("goods/editGoods", params)
                  .then((response) => {
                    this.activeName = "second";
                    this.getComboList();
                  });
              }
            );
            this.loading = false;
          } else {
            this.$store
              .dispatch("goods/editGoods", params)
              .then((response) => {
                this.activeName = "second";
                this.getComboList();
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName("is-error");
            isError[0].querySelector("input").focus();
          }, 100);
          this.loading = false;
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.w-900 >>> .el-upload-list__item-name {
  position: absolute;
  display: inline-block;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  text-align: center;
  color: white;
  font-size: 13px;
  background: rgba(0, 0, 0, 0.5);
}
.w-900 >>> .el-upload-list__item-name .el-icon-document:before {
  content: "";
}
</style>
<style lang="scss" scoped>
.app-main-height {
  .el-select {
    margin-right: 15px !important;
  }
  .el-input {
    width: 400px;
  }
  .el-textarea {
    width: 400px;
  }
}
.imgFile {
  width: 98px;
  height: 40px;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
  input {
    position: absolute;
    opacity: 0;
    left: 0;
    top: 0;
    width: 98px;
    height: 40px;
  }
}
.ql-toolbar {
  .ql-container {
    height: 500px;
  }
}
.text {
  color: #333;
  font-size: 12px;
}
.w-900 {
  width: 900px !important;
}
</style>
