<template>
  <div class="mod-config">
    <el-dialog
      :title="`${isEdit ? '编辑' : '充值'}湖分`"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <div v-if="dialogVisible">
        <el-form
          :model="addPointsForm"
          ref="addPointsForm"
          label-width="110px"
          :rules="dataRule"
        >
          <!-- <div style="background-color: #f0f0f0;padding:0 10px;box-sizing: border-box;color: #000;">
                        <p>绑定用户</p>
                    </div> -->
          <template v-if="pageType == 'label'">
            <el-form-item
              label="手机号/邮箱："
              prop="userKey"
              class="form_item"
            >
              <div style="display: flex;align-items: center;">
                <el-autocomplete
                  v-if="!isEdit"
                  style="width: 400px;"
                  v-model="addPointsForm.userKey"
                  :fetch-suggestions="loadAll"
                  placeholder="请输入手机号/邮箱"
                  @select="handleSelect"
                >
                  <template #default="{ item }">
                    <div class="custom-item">
                      <span>{{ item.tel ? item.tel : item.email }}</span>
                      <span
                        style="color: gray; margin-left: 10px;"
                        v-if="item.name"
                        >({{ item.name }})</span
                      >
                    </div>
                  </template>
                </el-autocomplete>
                <span v-if="isEdit">{{ addPointsForm.userKey }}</span>
              </div>
            </el-form-item>
            <el-form-item
              label="用户姓名："
              style="width: 400px;"
              v-if="addPointsForm.userId"
              prop="user"
              class="form_item"
            >
              <div>
                <!-- <span
                style="width: 110px;display: inline-block;text-align: right;"
                >用户姓名：</span
              > -->
                {{ addPointsForm.userName ? addPointsForm.userName : "-" }}
              </div></el-form-item
            >
          </template>
          <template v-if="pageType == 'user'">
            <el-form-item label="用户：" prop="user" class="form_item">
              <div style="display: flex;align-items: center;">
                {{ dataInfo.tel ? dataInfo.tel : dataInfo.email }}
                <span v-if="dataInfo.name">（ {{ dataInfo.name }}）</span>
              </div>
            </el-form-item>

            <el-form-item label="湖分分类" prop="type" class="form_item">
              <div>
                <el-select
                  :show-all-levels="false"
                  v-model="addPointsForm.type"
                  :options="cateOptions"
                  placeholder="请选择湖分分类"
                  @change="handleChange"
                >
                  <el-option
                    v-for="item in cateOptions"
                    :key="item.id"
                    :label="item.dictValue"
                    :value="item.dictType"
                  >
                  </el-option
                ></el-select></div
            ></el-form-item>
          </template>

          <el-form-item label="充值湖分" prop="score">
            <el-input-number
              :min="0"
              v-model="addPointsForm.score"
              placeholder="请输入湖分"
            >
            </el-input-number>
          </el-form-item>

          <el-form-item label="充值明细">
            <el-input
              style="width: 400px;"
              type="textarea"
              rows="5"
              v-model="addPointsForm.detail"
              placeholder="操作说明"
            >
            </el-input>
          </el-form-item>

          <!-- <el-select v-model="dataForm.expire" placeholder="证书分类" 
        @change="
        pageIndex = 1;
            getDataList();">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
          <!-- </el-form-item> -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('addPointsForm')">
          确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import global from "../../common/common.vue"; //引入共用组间
import debounce from "lodash/debounce"; //导入lodash中的debounce
import AddOrUpdate from "@/views/components/commonBookTags/bookTagsForm.vue";
import commonShop from "@/views/components/commonBookTags/shopproduct.vue";
import commonShopTable from "@/views/components/commonBookTags/shopproductTable.vue";
import commonTree from "@/views/components/commonBookTags/tags.vue";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
  ["blockquote", "code-block"], //引用，代码块
  [{ header: 1 }, { header: 2 }], // 几级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序列表，无序列表
  [{ script: "sub" }, { script: "super" }], // 下角标，上角标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  [{ direction: "rtl" }], // 文字输入方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 颜色选择
  [
    {
      font: [
        "SimSun",
        "SimHei",
        "Microsoft-YaHei",
        "KaiTi",
        "FangSong",
        "Arial"
      ]
    }
  ], // 字体
  [{ align: [] }], // 居中
  ["clean"], // 清除样式,
  ["link", "image"] // 上传图片、上传视频
];
// import dialogComponent from './seckillprodrelation'
export default {
  props: ["data", "pageType", "dataInfo"],
  data() {
    return {
      selectLabelId: "",
      isUploading: false, // 上传过程中是否显示加载动画
      isUploading: false, // 上传过程中是否显示加载动画
      isEdit: false, // 上传过程中是否显示加载动画
      dialogImageUrl: "",
      dialogVisibleImg: false,
      disabled: false,
      restaurants: [],
      fileList: [],
      options: [],
      cateOptions: [],
      state: "",
      timeout: null,
      addPointsForm: {},
      baseUrl: global.baseUrl,
      isEdit: false,
      checkAll: false,
      isIndeterminate: true,
      dialogVisible: false,
      urlList: {},
      activeName: "first",
      addForm: {},
      audioFileList: [],
      isFresh: false,
      dataRule: {}
    };
  },
  components: {
    AddOrUpdate,
    commonShop,
    commonTree,
    commonShopTable,
    quillEditor
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  activated() {
    this.isEdit = false;
    // this.getDataList();
  },
  methods: {
    remoteMethod(query) {
      console.log(query, "query", this.addPointsForm.key);
      // return false
      if (this.addPointsForm.key !== "") {
        let data = {
          title: query //关键字
        };
        this.totalLaoding = true;
        this.$http({
          url: this.$http.adornUrl("/master/userManage/courseAndChildrenList"),
          method: "post",
          data: this.$http.adornData(data)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.options = data.list;
          } else {
            this.options = [];
          }
          this.totalLaoding = false;
          if (data.code !== 0) return this.$message.error(data.msg);
        });
      } else {
        this.options = [];
        this.totalLaoding = false;
      }
    },
    handleChange(e) {
    console.log('e at line 250:', e)
      this.addPointsForm.type = e.toString();
      this.$forceUpdate()
    },
    getCateList() {
      this.$http({
        url: this.$http.adornUrl(
          "/master/userContribution/getUserContributionLabelList"
        ),
        method: "post",
        data: this.$http.adornData({})
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.cateOptions = data.labelList;
        } else {
          this.cateOptions = [];
        }
        this.totalLaoding = false;
        if (data.code !== 0) return this.$message.error(data.msg);
      });
    
    },
    loadAll(queryString, cb) {
      if (queryString == "") {
        return false;
      }
      this.$http({
        // url: this.$http.adornUrl('/book/user/list'),
        url: this.$http.adornUrl("/book/user/getUserList"),
        method: "post",
        data: this.$http.adornData({
          page: 1,
          limit: 9999,
          key: queryString
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          var arr = data.user.records;
          console.log("arr at line 467:", arr);
          cb(arr);
        } else {
          cb([]);
        }
      });
    },

    createStateFilter(queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      console.log(item);
      this.addPointsForm.userKey = item.tel ? item.tel : item.email;
      this.addPointsForm.userName = item.name;
      this.addPointsForm.userId = item.id;
    },
    init(type, data) {
      this.getCateList();
      console.log("data at line 372:", data);
      this.addPointsForm = {};
      this.fileList = [];
      this.isEdit = type == "edit" ? true : false;
      if (this.pageType == "label") {
        this.dataRule = {
          score: [
            {
              required: true,
              message: "请输入湖分"
              // trigger: "change",
            }
          ]
        };
      } else {
        this.dataRule = {
          // type: [
          //   {
          //     required: true,
          //     message: "请选择湖分分类"
          //     // trigger: "change",
          //   }
          // ],
          score: [
            {
              required: true,
              message: "请输入湖分"
              // trigger: "change",
            }
          ]
        };
      }
      if (data) {
        
        this.remoteMethod(this.addPointsForm.courseName);
        if (this.addPointsForm.images) {
          this.fileList = this.addPointsForm.images
            .split(",")
            .map((image, i) => ({
              uid: i, // 假设 id 是唯一标识符
              name: i, // 文件名
              status: "done", // 状态
              url: image // 文件 URL
            }));
          console.log("this.fileList at line 308:", this.fileList);
        }
      } else {
        this.addPointsForm = {};
      }
      if (this.pageType == "label") {
        if (data.userId) {
          this.addPointsForm.userKey = data.tel ? data.tel : data.email;
          this.addPointsForm.userName = data.name;
          this.addPointsForm.userId = data.id;
        }
      } else {
        this.addPointsForm.userKey = this.dataInfo.tel
          ? this.dataInfo.tel
          : this.dataInfo.email;
        this.addPointsForm.userName = this.dataInfo.name;
        this.addPointsForm.userId = this.dataInfo.id;
      }

console.log('data at line 395:', data)
this.addPointsForm.type = data.type? data.type : "";
      this.dialogVisible = true;
    },

    handleSubmit: debounce(async function() {
      if(this.addPointsForm.type == ""){
        this.$message({
          message: "请选择湖分分类",
          type: "error"
        });
        return false;
      }
      this.$refs["addPointsForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              "/master/userContribution/saveUserContribution"
            ),
            method: "post",
            data: this.$http.adornData({
              userId:
                this.dataInfo && this.dataInfo.id
                  ? this.dataInfo.id
                  : this.addPointsForm.userId,
              score: this.addPointsForm.score,
              detail: this.addPointsForm.detail
                ? this.addPointsForm.detail
                : "",
              type: this.addPointsForm.type,
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.dialogVisible = false;
              this.$nextTick(() => {
                this.$emit("refresh");
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }, 200),

    onSuccessImg(response, file, fileList) {
      // 上传成功后，直接将返回的 URL 放到 file 对象中
      file.uploading = false;
      file.url = response.url; // 假设返回的数据包含文件的 url 地址
      this.fileList = fileList; // 更新 fileList
    },

    beforeUpload(file) {
      // 在文件上传之前，设置文件的上传状态
      file.uploading = true;
    },
    onProgress(event, file, fileList) {
      // 进度更新时，文件状态可以继续保持上传中
      file.uploading = true;
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(f => f.uid !== file.uid); // 删除文件
    },
    handleDownload(file) {
      const link = document.createElement("a");
      link.href = file.url;
      link.download = file.name;
      link.click();
    },
    selectChange(val) {
      console.log("options", this.options);
      //   this.getCate(val)
    },
    handlePictureCardPreview(file) {
      // 图片预览逻辑
    }
  }
};
</script>
<style lang="less" scoped></style>
