<template>
  <el-dialog
    width="700px"
    :title="`${!dataForm.id?'新增':'修改'}广告`"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="handlereset"
    style="height: auto;"
  >
    <div style="margin-bottom: 60px;">
      <el-form
        style="height: auto;"
        class="addFormBox"
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="80px"
      >
        <el-form-item label="发布APP" prop="title">
          <el-select v-model="dataForm.appType" placeholder="请选择">
            <el-option
              v-for="item in APPList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="广告类型" prop="type">
          <el-radio-group v-model="dataForm.type" @input="selectType">
            <el-radio
              v-for="item in typeList"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联商品" prop="type" v-if="dataForm.type == 0">
          <div>
            <el-button type="primary" size="mini" @click="showProTable"
              >关联商品</el-button
            >
          </div>
          <div
            v-if="JSON.stringify(bindProductData) != '{}'"
            style="background: #f5f5f5;border-radius: 10px;padding:10px 20px;"
          >
            <div style="line-height: 20px;font-weight: bold;">
              商品信息

              <span
                style="float: right;color: red;cursor: pointer;"
                @click="clearBind"
                >解绑</span
              >
            </div>
            <div
              style="margin-top: 10px;display: flex;align-items: center;
            justify-content: space-between;"
            >
              <div style="background-color: #b0b0b0;width: 50px;height: 70px;">
                <img
                  v-if="
                    JSON.stringify(bindProductData) != '{}' &&
                      bindProductData.productImages != ''
                  "
                  :src="bindProductData.productImages"
                  width="50"
                  height="70"
                  class="tableImg"
                />
                <span
                  v-else
                  style="text-align: center;line-height: 70px;font-size: 10px;"
                  >暂无封面图</span
                >
              </div>
              <div style="width: calc(100% - 60px);line-height: 20px;">
                <div>
                  <span style="font-weight: bold;">商品ID：</span>
                  {{ bindProductData.productId }}
                </div>
                <div>
                  <span style="font-weight: bold;">商品名称：</span
                  >{{ bindProductData.productName }}
                </div>
                <div>
                  <span style="font-weight: bold;">价格：</span
                  >{{ bindProductData.price }}
                </div>
                <div>
                  <span style="font-weight: bold;">活动价：</span
                  >{{ bindProductData.activityPrice }}
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="广告图片" prop="type">
          <el-upload
            :limit="1"
            class="el-uploadfeng"
            :action="baseUrl + '/oss/fileoss'"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :file-list="fileList"
            :on-success="handlePicSuccess"
            accept=".jpeg,.jpg,.gif,.png"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog
            :visible.sync="dialogVisible"
            :append-to-body="true"
            custom-class="iconBox"
          >
            <img width="100%" :src="dataForm.icon" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handlereset">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <commonShopTable
      ref="commonShopTable"
      currentType="courseLinkPro"
      @submit="bindProduct"
    ></commonShopTable>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce"; //导入lodash中的debounce
import commonShopTable from "./shopproductTable.vue";
import global from "@/views/common/common.vue"; //引入共用组间
export default {
  props: ["typeList", "APPList"],
  data() {
    return {
      bindProductData: {}, // 封面图
      fileList: [], // 封面图
      baseUrl: global.baseUrl,
      visible: false,
      // 富文本编辑器配置

      props: {
        dictType: "",
        dictValue: ""
      },
      gushuList: [],

      restaurants: [],
      author: "",
      publisherList: [],
      fileList: [],
      fileListNovel: [],
      dialogImageUrl: "",
      dialogVisible: false,
      dataForm: {
        type: 0,
        app_type: 0
      },

      dataRule: {
        // url: [{ required: true, message: "链接地址不能为空", trigger: "blur" }]
      },
      urlList: {
        // info: "/master/message/getMessageById",
        add: "/master/mainAd/addMainAd",
        edit: "/master/mainAd/editMainAd",
        productInfo: "/master/shopProduct/getProductDetail"
      }
    };
  },
  components: { commonShopTable },
  created() {},
  mounted() {
    // this.restaurants = this.loadAll();
  },
  methods: {
    selectType() {
      this.bindProductData = {};
      this.dataForm.relationId = "";
      this.$forceUpdate();
    },
    clearBind() {
      this.bindProductData = {};
      this.dataForm.relationId = "";
      this.$forceUpdate();
    },
    async bindProduct(data) {
      console.log("data at line 186:", data);
      this.dataForm.relationId = data.productId;
      this.bindProductData = data;
      // await this.getProductInfo();

      this.$forceUpdate();
    },
    showProTable(data) {
      console.log("data", data);
      this.$nextTick(() => {
        this.$refs.commonShopTable.open();
      });
    },
    handleRemove(file, fileList) {
      this.dataForm.icon = "";
      // this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
    },
    handlePicSuccess(res, file) {
      if (res.msg == "success") {
        this.dataForm.icon = res;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    changeType(e) {
      console.log("e at line 256:", e);
      if (e == 0) {
        this.dataForm.content = "";
      } else {
        this.dataForm.url = "";
      }
    },
    contentUploadSuccess(res, file) {
      // console.log(res)
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        this.$message.error("图片插入失败！");
      }
    },
    // 失去焦点事件
    onEditorBlur(quill) {
      //  console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      //console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    },
    init(row) {
      this.dataForm = { ...row };
      if (this.dataForm.icon) {
        this.fileList.push({
          name: this.dataForm.icon,
          url: this.dataForm.icon
        });
      }
      if (this.dataForm.shopProduct) {
        this.bindProductData = { ...this.dataForm.shopProduct };
      } else {
        this.bindProductData = {};
      }
      this.$forceUpdate();
      this.visible = true;
      this.$nextTick(()=>{
        this.$refs.dataForm.clearValidate();
      })
      

    },

    async getProductInfo() {
      if (this.dataForm.relationId == "" || this.dataForm.type != 0) {
        return false;
      }

      await this.$http({
        url: this.$http.adornUrl(this.urlList.productInfo),

        method: "POST",
        data: {
          productId: this.dataForm.relationId
        },
        header: {
          //默认 无 说明：请求头
          "Content-Type": "application/json"
        }
      }).then(({ data }) => {
        console.log("data at line 273:", data);

        this.bindProductData = data.detail.detail;
      });
    },
    // 表单提交
    dataFormSubmit: debounce(async function () {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.dataForm.appType == 0 || this.dataForm.appType) {
            if (this.dataForm.type == 0 && this.dataForm.relationId == "") {
              this.$message.error("请选择关联商品");
              return;
            }
          } else {
            this.$message.error("请选择发布APP");
            return;
          }
          if (this.dataForm.type == 0 || this.dataForm.type) {
          } else {
            this.$message.error("请选择广告类型");
            return;
          }
          if (!this.dataForm.icon || this.dataForm.icon == "") {
            this.$message.error("请上传图片");
            return;
          }
          console.log("this.dataForm.type at line 332:", this.dataForm);

          this.$http
            .request({
              url: this.$http.adornUrl(
                this.dataForm.id ? this.urlList.edit : this.urlList.add
              ),
              method: "POST",
              data: this.dataForm,
              header: {
                //默认 无 说明：请求头
                "Content-Type": "application/json"
              }
            })
            .then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
        }
      });
    },200),
    handlePicSuccess(res, file) {
      // console.log(res,'res')
      if (res.msg == "success") {
        this.dataForm.icon = res.url;
        this.fileList.push({
          name: file.name,
          url: res.url
        });
        //  console.log(this.dataForm.image,'image')
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    handleRemove(file, fileList) {
      this.dataForm.icon = "";
      this.fileList = [];
      this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
    },
    handlePictureCardPreview(file) {
      this.dataForm.icon = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    handlereset() {
      (this.fileList = []), (this.fileListNovel = []), (this.visible = false);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemoveNovel(file) {
      this.dataForm.novel = "";
    },
    handleNovelSuccess(file) {
      this.dataForm.novel = file.url;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-uploadfeng {
  /deep/ .el-upload-list__item {
    width: 120px;
    height: 120px;
    .el-upload-list__item-thumbnail {
      object-fit: cover !important;
    }
  }

  /deep/ .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 110px;
  }
}

/deep/ .addFormBox.el-form-item {
  margin-bottom: 10px !important;
}

/deep/ .ql-container {
  min-height: 400px !important ;
}
/deep/ .el-radio {
  margin-right: 0 !important;
}
/deep/ .iconBox {
  background: transparent !important;
}
</style>
