<template>
  <div class="tenant">
    <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row
             :selectConfig="selectConfig" :table-events="{
          select: select,
        }" :action-list="[
        {
          text: '添加封面',
          action: () => openModal('add'),
        },
      ]" @get-list="getList">

      <template #coverUrl="{ item }">
        <div v-if="item.coverList.length > 0">
          <img :src="item.coverList[0].fileUrl" class="pic" @click="handleClickFile(item.coverList[0])" />
        </div>
        <div v-else></div>
      </template>

      <template #audioUrl="{ item }">
        <div v-if="item.audioList.length > 0">
          <audio controls>
            <source :src="item.audioList[0].fileUrl" type="audio/mp3">
          </audio>
        </div>
        <div v-else></div>
      </template>
    </byTable>

    <el-dialog z-index="1100" :title="modalType == 'add' ? '添加封面信息' : '编辑封面信息'" v-if="dialogVisible" v-model="dialogVisible" width="800px"
               v-loading="loading">
      <el-row style="width: 100%">
        <el-col :span="15">
          <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
            <template #coverList>
              <el-row style="width: 100%">
                <el-col :span="24">
                  <el-form-item prop="coverList">
                    <el-upload class="avatar-uploader" action="https://winfaster.obs.cn-south-1.myhuaweicloud.com" :data="uploadDataOne"
                               :show-file-list="false" accept=".gif, .jpeg, .jpg, .png" :on-success="coverListSuccess" :before-upload="uploadFileOne">
                      <el-image v-if="formData.data.coverList && formData.data.coverList.length > 0" :src="formData.data.coverList[0].fileUrl"
                                fit="scale-down" class="avatar" />
                      <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                    <el-button class="delete-btn" type="danger" v-if="formData.data.coverList && formData.data.coverList.length > 0"
                               @click="formData.data.coverList = [];formData.data.coverUrl=''">
                      删除
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template #audioList>
              <el-row style="width: 100%">
                <el-col :span="24">
                  <el-form-item prop="audioList">
                    <el-upload class="avatar-uploader" action="https://winfaster.obs.cn-south-1.myhuaweicloud.com" :data="uploadDataTwo"
                               :show-file-list="false" accept="audio/*" :on-success="audioListSuccess" :before-upload="uploadFileTwo">
                      <audio controls style="margin-top: 20px" v-if="formData.data.audioList && formData.data.audioList.length > 0">
                        <source :src="formData.data.audioList[0].fileUrl" type="audio/mp3">
                      </audio>
                      <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                    <el-button class="delete-btn" type="danger" v-if="formData.data.audioList && formData.data.audioList.length > 0"
                               @click="formData.data.audioList = [];formData.data.audioUrl=''">
                      删除
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </byForm>
        </el-col>
        <el-col :span="9">
          <div class="blessingClass">
            <div :style="coverStyle">

              <div :style="fontStyle">
                <p>xxxxx:</p>
                <p>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;朋友生日到，千里送鹅毛。信息虽一毛，情谊伴到老。今生有缘遇，相知无争吵。虽非日夜伴，心中牵挂绕。问候不可少，祝福也送到。愿你身体健，快乐无烦恼；愿你事业顺，业绩步步高；愿你幸福笑，如意直到老。祝生日快乐！
                </p>
              </div>
            </div>
          </div>
        </el-col>

      </el-row>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="large" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, nextTick, reactive, ref } from "vue";
const { proxy } = getCurrentInstance();

const router = useRouter();
const loading = ref(false);
const coverTypeList = ref([]);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});

let rules = ref({
  coverType: [{ required: true, message: "请选择封面类型", trigger: "change" }],
  coverName: [{ required: true, message: "请输入封面名称", trigger: "blur" }],
  coverUrl: [{ required: true, message: "请上传封面", trigger: "blur" }],
  audioUrl: [{ required: true, message: "请上传音频", trigger: "blur" }],
});
let dialogVisible = ref(false);
let subFlag = ref(false);
let modalType = ref("add");
const selectConfig = computed(() => {
  return [
    {
      label: "封面类型",
      prop: "status",
      data: coverTypeList.value,
    },
  ];
});

const config = computed(() => {
  return [
    {
      attrs: {
        label: "封面类型",
        prop: "coverType",
        width: "240",
        align: "left",
      },
      render(type) {
        return proxy.dictValueLabel(type, coverTypeList.value);
      },
    },
    {
      attrs: {
        label: "封面名称",
        prop: "coverName",
        align: "left",
      },
    },
    {
      attrs: {
        label: "封面",
        slot: "coverUrl",
        width: 100,
        align: "left",
      },
    },
    {
      attrs: {
        label: "音频",
        slot: "audioUrl",
        width: 320,
        align: "left",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm(
                "此操作将永久删除该数据, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                //删除
                proxy
                  .post("/blessingCover/delete", {
                    id: row.id,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    coverList: [],
    audioList: [],
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);

const formConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "coverType",
      label: "封面类型",
      data: coverTypeList.value,
      required: true,
    },
    {
      type: "input",
      prop: "coverName",
      label: "封面名称",
      required: true,
    },

    {
      type: "slot",
      slotName: "coverList",
      prop: "coverUrl",
      label: "封面文件",
      required: true,
    },
    {
      type: "slot",
      slotName: "audioList",
      prop: "audioUrl",
      label: "音频文件",
      required: true,
    },
  ];
});

const getDictlist = async () => {
  proxy.getDictOne(["cover_type"]).then((res) => {
    coverTypeList.value = res["cover_type"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/blessingCover/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    content: "",
  };
  coverStyle.value = null;
  previewBlessingInit();
};
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/blessingCover/detail", { id: row.id }).then((res) => {
    formData.data = res;
    dialogVisible.value = true;

    proxy
      .post("/fileInfo/getList", { businessIdList: [res.id], fileType: 1 })
      .then((resFile) => {
        formData.data.coverList = resFile[res.id];
        formData.data.coverUrl = resFile[res.id][0].fileUrl;

        previewBlessing();
      });
    proxy
      .post("/fileInfo/getList", { businessIdList: [res.id], fileType: 2 })
      .then((resFile) => {
        formData.data.audioList = resFile[res.id];
        formData.data.audioUrl = resFile[res.id][0].fileUrl;
      });
  });
};

const submitForm = () => {
  byform.value.handleSubmit(() => {
    submitLoading.value = true;
    proxy.post("/blessingCover/" + modalType.value, formData.data).then(
      () => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        submitLoading.value = false;
      }
    );
  });
};

const uploadDataOne = ref({});
const uploadFileOne = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadDataOne.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const uploadDataTwo = ref({});
const uploadFileTwo = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadDataTwo.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};

const coverListSuccess = (response, uploadFile) => {
  formData.data.coverList = [
    {
      id: uploadFile.raw.id,
      fileName: uploadFile.raw.fileName,
      fileUrl: uploadFile.raw.fileUrl,
    },
  ];

  formData.data.coverUrl = uploadFile.raw.fileUrl;

  setTimeout(() => {
    previewBlessing();
  }, 500);

};
const audioListSuccess = (response, uploadFile) => {
  formData.data.audioList = [
    {
      id: uploadFile.raw.id,
      fileName: uploadFile.raw.fileName,
      fileUrl: uploadFile.raw.fileUrl,
    },
  ];

  formData.data.audioUrl = uploadFile.raw.fileUrl;
};

const handleClickFile = (file) => {
  window.open(file.fileUrl, "_blank");
};

const coverStyle = ref({});
const fontStyle = ref({});
//模拟获取屏幕的宽高
var offsetWidth = 262,
  offsetHeight = 520;

const previewBlessingInit = () => {
  coverStyle.value = {
    width: offsetWidth + "px",
    height: offsetHeight + "px",
    position: "relative",
  };

  fontStyle.value = {
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    margin: "0 25px",
  };
};
const previewBlessing = () => {
  //背景图片
  const coverUrl = formData.data.coverUrl;

  //获取图片的宽高
  var img = new Image();
  img.src = coverUrl;
  var naturalWidth = img.width,
    naturalHeight = img.height;

  //等比自适应
  var backgroundSize = "";
  if (naturalWidth / naturalHeight > offsetWidth / offsetHeight) {
    backgroundSize = "100% auto";
  } else {
    backgroundSize = "auto 100%";
  }
  coverStyle.value = {
    backgroundImage: "url(" + coverUrl + ") ",
    width: offsetWidth + "px",
    height: offsetHeight + "px",
    backgroundRepeat: "no-repeat",
    backgroundSize: backgroundSize,
    backgroundPosition: "center center",
    position: "relative",
  };

  fontStyle.value = {
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    margin: "0 25px",
  };
};

getDictlist();
getList();
</script>

<style lang='scss' scoped>
.tenant {
  padding: 20px;
  .delete-btn {
    margin-top: 10px;
    margin-left: 25px;
  }
}
.avatar-uploader .avatar {
  width: 110px;
  height: 110px;
  display: block;
  background-color: black;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}

.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}

.blessingClass {
  background-image: url("../../../assets/victoria/sjk.jpg");
  background-size: cover;
  height: 600px;
  width: 300px;

  padding: 40px 19px;
}
</style>
