<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="600px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="form-dialog-box"
    v-loading="loading"
    :element-loading-text="loadingText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
      <el-form :model="form" ref="form" :rules="rules" label-width="130px">
        <el-form-item label="类型名称" prop="name">
          <el-input style="width: 350px;" v-model="form.name" placeholder="请输入类型名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="点位图标" prop="iconImg">
          <div
          style="width: 120px;"
          v-loading="actionUrlLoading"
          element-loading-text="上传中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          >
            <el-upload
              class="avatar-uploader"
              :action="actionUrl"
              :data="{
                bucket: 'tourism'
              }"
              :show-file-list="false"
              accept=".jpg, .png, jpeg"
              :on-success="handleAvatarSuccess"
              :on-progress="handleAvatarProgress"
              :before-upload="beforeAvatarUpload"
              :disabled="actionUrlLoading"
              :on-error="handleAvatarError"
              >
              <img v-if="form.iconImg" style="width: 100px;height: 100px;background-color: rgba(211,211,211,0.6);" :src="form.iconImg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <span>建议尺寸40*40,支持jpg,png,gif,支持1MB大小以内的图片上传</span>
        </el-form-item>
        <el-form-item label="点位图标" prop="iconPath">
          <div
          style="width: 120px;"
          v-loading="actionUrlLoading"
          element-loading-text="上传中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          >
            <el-upload
              class="avatar-uploader"
              :action="actionUrl"
              :data="{
                bucket: 'tourism'
              }"
              :show-file-list="false"
              accept=".jpg, .png, jpeg"
              :on-success="handleAvatarSuccess1"
              :on-progress="handleAvatarProgress1"
              :before-upload="beforeAvatarUpload1"
              :disabled="actionUrlLoading1"
              :on-error="handleAvatarError1"
              >
              <img v-if="form.iconPath" style="width: 100px;height: 100px;background-color: rgba(211,211,211,0.6);" :src="form.iconPath" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <span>建议尺寸40*40,支持jpg,png,gif,支持1MB大小以内的图片上传</span>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer" v-if="formStatus==1">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        :loading="loading"
        element-loading-text="提交中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      > 
        {{ loading ? '提交中...' : '保存' }}
      </el-button>
    </span>
    <!-- 添加或修改对话框 End -->
  </el-dialog>
</template>

<script>
import { 
  getTableDeatilsByIdApi,
  updateTableApi,
  addTableApi,
  listTableApi
 } from '@/api/CURD'

export default {
  name: "addAndEdit",
  dicts: [],
  data() {
    return {
      title: "",
      model: "", // EDIT: 编辑模式 ADD : 新增模式  EDITInit : 编辑模式（需要请求详情）
      open: false,
      loading: false,
      loadingText: "拼命加载数据中...",
      formStatus: null, // 0/null : 加载中 1 : 获取详情成功 2  : 获取详情失败 
      configUrl: {
        add: '/merchant/merchantMapMarkType/insertOrUpdate', // 新增地址
        details: '/merchant/advList/selectById', // 详情地址
        edit: '/merchant/merchantMapMarkType/insertOrUpdate', // 编辑地址
      },
      form: {
        id: undefined,
      },
      rules: {
        name: [{ required: true, message: "请输入类型名称", trigger: ["change","blur"] }],
        iconImg: [{ required: true, message: "请上传图片", trigger: ["change","blur"] }],
      },
      scenicAreaProducts: [],// 景点产品关联
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除文本格式
            ['image', 'video'] // 链接、图片、视频
          ]
        },
        placeholder: '请输入正文'
      },

      //  上传文件
      actionUrl: process.env.VUE_APP_BASE_API + process.env.VUE_APP_UPLOAD_IMAGE,
      actionUrlLoading: false,
      actionUrlLoading1: false,
    };
  },
  methods: {
    async initData(title , model,row){
      this.title = title
      this.open = true
      this.loadingText = "拼命加载数据中..."
      this.loading = true
      this.actionUrlLoading = false
      this.model = model
      this.formStatus = 0
      if(model=='ADD') { // 新增
        this.$set(this,'form',row)
        this.formStatus = 1
      }else if(model=='EDIT') { // 新增
        let obj = {
          ...row
        }
        this.$set(this,'form',obj)
        this.formStatus = 1
      }else if(model=='EDITInit') { // 新增
        await this.getTableDeatilsFun(row)
      }
      this.loading = false
      this.$nextTick(()=>{
        if(this.$refs["form"]) {
          this.$refs["form"].clearValidate();
        }
      })
    },
    /** 获取详情 */
    async getTableDeatilsFun(row) {
      const id = row.id
      this.loading = true
      try {
        let res = await getTableDeatilsByIdApi(this.configUrl.details,{id})
        if(res.code == 200) {
          let obj = {
            ...res.data
          }
          this.$set(this,'form',JSON.parse(JSON.stringify(obj)))
          this.formStatus = 1
        }else {
          this.$message.error('获取详情失败!!!');
          this.formStatus = 2
          this.loading = false
          this.open = false;
        }
        this.loading = false
      } catch (error) {
        console.error('获取详情失败!!!!',error)
        this.formStatus = 2
        this.loading = false
        this.open = false;
      }
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loadingText = "提交数据中..."
          this.loading = true
          if (this.model != 'ADD') {
            addTableApi(
              this.configUrl.edit,{
                ...this.form
              }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.loading = false
              this.open = false;
              this.$emit('refresh')
            }).catch(()=>{
              this.$message.error("修改失败!!!");
              this.loading = false
            })
          } else {
            addTableApi(this.configUrl.edit,{
                ...this.form
              }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.loading = false
              this.open = false;
              this.$emit('refresh')
            }).catch(()=>{
              this.$message.error("新增失败!!!");
              this.loading = false
            })
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      if(this.$refs["form"]) {
        this.$refs["form"].clearValidate();
      }
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**  上传图片  */
    handleAvatarSuccess(res, file) {
      console.log("res, file",res, file)
      this.actionUrlLoading = false
      if(res.code != 200) {
        this.$set(this.form,'iconImg',null) 
      }else {
        this.$set(this.form,'iconImg',res.data.url) 
      }
      
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 <= 1;
      let testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
      let typeList = ['png','jepg','jpg','gif']
      const isJPG = typeList.includes(testmsg);
      if (!isJPG) {
        this.$message.error(`上传图片图片只能是 ${typeList} 格式!`);
      }
      if (!isLt2M) {
        this.$message.error('上传图片图片大小不能超过 2MB!');
      }

      let isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            let valid = img.width == 40 && img.height == 40;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传图片尺寸只能是 40*40 px !");
            return Promise.reject();
          }
        );
      return isJPG && isLt2M && isSize;
    },
    handleAvatarProgress(){
      this.actionUrlLoading = true
    },
    handleAvatarError() {
      this.actionUrlLoading = false
    },

    /**  上传图片  */
    handleAvatarSuccess1(res, file) {
      console.log("res, file",res, file)
      this.actionUrlLoading = false
      if(res.code != 200) {
        this.$set(this.form,'iconPath',null) 
      }else {
        this.$set(this.form,'iconPath',res.data.url) 
      }
      
    },
    beforeAvatarUpload1(file) {
      const isLt2M = file.size / 1024 / 1024 <= 1;
      let testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
      let typeList = ['png','jepg','jpg','gif']
      const isJPG = typeList.includes(testmsg);
      if (!isJPG) {
        this.$message.error(`上传图片图片只能是 ${typeList} 格式!`);
      }
      if (!isLt2M) {
        this.$message.error('上传图片图片大小不能超过 2MB!');
      }

      let isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            let valid = img.width == 40 && img.height == 40;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传图片尺寸只能是 40*40 px !");
            return Promise.reject();
          }
        );
      return isJPG && isLt2M && isSize;
    },
    handleAvatarProgress1(){
      this.actionUrlLoading1 = true
    },
    handleAvatarError1() {
      this.actionUrlLoading1 = false
    }
  },
};
</script>

<style lang="scss" scoped>
.form-dialog-box {
  padding: 0 30px;
  padding: 0 30px;
  min-height: 50vh;
  max-height: 65vh;
  overflow-y: auto;
  >div {
    width: 100%;
    min-height: 50vh;
  }
  .form-title {
    padding: 0 0 10px 0;
    span {
      display: flex;
      color: rgba(65,80,88,1);
      font-size: 16px;
      font-family: SourceHanSansSC;
      font-weight: 700;
      line-height: 23px;
      border-left: 4px solid rgb(22, 132, 252);
      padding-left: 10px;
    }
    
  }
  ::v-deep .ql-editor {
    height: 400px;
  }
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}
.el-table{
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}

.area-container {
  min-height: 400px;
}

::v-deep .area-wrap-city.el-cascader {
  line-height: normal;
  .el-input {
    cursor: pointer;
    width: 100% !important;
    height: 28px !important;
    .el-input__inner {
      display: none !important;
    }
    span.el-input__suffix {
      position: inherit !important;
      i.el-input__icon {
        line-height: inherit;
        margin-left: 5px;
      }
    }

    .el-input__wrapper {
      box-shadow: none;
      input {
        display: none;
      }
    }
  }

  .el-cascader__tags {
    display: none;
  }
}

.area-city-popper {
  .el-cascader-panel {
    .el-scrollbar.el-cascader-menu {
      .el-cascader-menu__wrap.el-scrollbar__wrap {
        height: 315px;
      }
    }
  }
}

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  ::v-deep .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
<style>
.custom-class-box {
  z-index: 999999 !important;
}
</style>