<template>
  <div class="edit-content">
    <div class="edit-form">
      <!-- <div class="edit-form-item">
        <p class="edit-label">正文</p>
        <div class="charpt-list form-content">
          <template v-for="(item, idx) in charptList" :key="idx">
            <div class="charpt-list-item">
              <p class="item-label">文章标题</p>
              <div class="item-input">
                <a-input
                  :maxLength="50"
                  v-model:value="item.title"
                  placeholder="请输入标题"
                  style="width:638px"
                />
              </div>
              <a
                href="javascript:;"
                class="delete-text"
                v-show="idx > 0"
                @click="deleteLine(idx)"
                >删除</a
              >
            </div>
            <div class="charpt-list-item bor-line">
              <p class="item-label">正文内容</p>
              <div class="item-input">
                <a-textarea
                  v-model:value="item.content"
                  placeholder="请输入正文"
                  :auto-size="{ minRows: 5, maxRows: 10 }"
                />
              </div>
            </div>
            <hr />
          </template>
          <div class="add-item" @click="addNewCharpt">
            添加新章节+
          </div>
        </div>
      </div> -->
      <div class="edit-form-item">
        <p class="edit-label">推广书籍</p>
        <div class="edit-form-select">
          <a-select
            v-model:value="bookId"
            placeholder="请选择推广书籍支持搜索"
            style="width: 200px"
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            @search="fetchBook"
            @change="selectBook"
            show-search
          >
            <template v-if="fetching" #notFoundContent>
              <a-spin size="small" />
            </template>
            <a-select-option v-for="d in bookList" :key="d.bid">
              {{ d.book_name }}
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div class="edit-form-item">
        <p class="edit-label">选择章节</p>
        <div class="edit-form-select">
          <a-select
            v-model:value="charptId"
            placeholder="选择章节"
            style="width: 200px"
          >
            <a-select-option v-for="d in charptList" :key="d.sequence">
              {{ d.name }}
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div class="edit-form-item">
        <p class="edit-label">顶部图片</p>
        <div class="choose-img">
          <div v-show="!selectImg" class="black-chos" @click="showModel">
            选择
          </div>
          <div class="img" v-show="selectImg">
            <img :src="chooseImgUrl" style="width:100%" @click="showModel" />
          </div>
        </div>
      </div>
      <div class="edit-form-item">
        <p class="edit-label">正文模板</p>
        <div class="template-list">
          <div
            v-for="(item, index) in templateList"
            v-html="item.content"
            :key="index"
            :class="[
              'template-item',
              index == templateChecked ? 'current' : '',
            ]"
            @click="chooseTemplate(item, index)"
          ></div>
        </div>
      </div>
      <div></div>
      <div>
        <Tinymce v-model="mycontent" :height="600">
          <a-button @click="importTemp" class="btns" type="primary"
            >导入模板</a-button
          >
        </Tinymce>
      </div>
      <div class="button-form">
        <a-button style="margin-right:20px" @click="goPrev">上一步</a-button>
        <a-button type="primary" @click="submitForm">保存</a-button>
      </div>
    </div>
    <a-modal
      v-model:visible="modelShow"
      title="顶部图片"
      @ok="handleSumbit"
      :width="1000"
    >
      <a-tabs v-model:activeKey="activeKey" @change="loadMore(1, true)">
        <a-tab-pane key="10" tab="女频"></a-tab-pane>
        <a-tab-pane key="11" tab="男频"></a-tab-pane>
        <a-tab-pane key="12" tab="活动"></a-tab-pane>
        <a-tab-pane key="14" tab="我的"></a-tab-pane>
      </a-tabs>
      <div class="radio-grouped" v-show="activeKey != 12 && activeKey != 14">
        <a-radio-group
          v-model:value="chooseType"
          style="margin: 0 auto"
          @change="loadMore(1, true)"
        >
          <a-radio-button value="1">现代</a-radio-button>
          <a-radio-button value="2">古代</a-radio-button>
        </a-radio-group>
      </div>
      <div class="upload-my" v-show="activeKey == 14">
        <a-upload
          v-model:file-list="fileList"
          :show-upload-list="false"
          :custom-request="onFileChange"
        >
          <a-button type="primary">
            点击上传
          </a-button>
        </a-upload>
      </div>
      <a-list
        class="loadmore-list"
        :loading="listLoading"
        item-layout="horizontal"
        :grid="{ gutter: 10, xs: 1, sm: 2, md: 4, lg: 4, xl: 6, xxl: 6 }"
        :data-source="dataList"
      >
        <template #loadMore>
          <div
            :style="{
              textAlign: 'center',
              marginTop: '12px',
              height: '32px',
              lineHeight: '32px',
            }"
          >
            <a-button
              v-show="!listLoading && showLoaderMore"
              @click="loadMore()"
              >加载更多</a-button
            >
          </div>
        </template>
        <template #renderItem="{ item, index }">
          <a-list-item>
            <div :class="['img-item', index == temChecked ? 'current' : '']">
            
                <img
                  :src="item.link"
                  @click="chooseImg(item, index)"
                  width="144"
                />
              
            </div>
          </a-list-item>
        </template>
      </a-list>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  onMounted,
  computed,
} from "vue";
import {
  getLandingPic,
  getLandingTempalte,
  landingBook,
  landingCharpter,
  setLandingBook,
  landingMypic,
  landingSaveMypic,
  onUpload,
} from "@/api";
import store from "@/store";
import { Tinymce } from "@/components/Tinymce/index";
import { message } from "ant-design-vue";
import useApp from "@/hooks/useApp";
import useDebounceFn from "@/hooks/useDebounceFn";
const StepTwo = defineComponent({
  name: "StepTwo",
  components: {
    Tinymce,
  },
  props: {
    content: Object,
    default() {
      return {};
    },
  },
  setup(props, { emit }) {
    const { route, router } = useApp();
    const state = reactive({
      fileList: ref<any>([]),
      bookId: "",
      charptId: "",
      fetching: false,
      bookList: ref<any>([]),
      charptList: ref<any>([]),
      mycontent: "",
      modelShow: false,
      selectImg: false,
      activeKey: "10",
      chooseType: "1",
      currentPage: 1,
      listLoading: false,
      showLoaderMore: true,
      dataList: [],
      chooseImgUrl: "",
      temItem: ref<any>({}),
      temChecked: ref<any>(null),
      templateItemChecked: ref<any>({}),
      templateChecked: ref<any>(null),
      templateList: ref<any[]>([]),
      stepOneTem: computed(() => store.getters.getOneTemp),
    });
    const addNewCharpt = () => {
      let data = {
        title: "",
        content: "",
      };
      state.charptList.push(data);
    };
    const deleteLine = (idx: number) => {
      state.charptList.splice(idx, 1);
    };
    //弹窗
    const showModel = () => {
      state.modelShow = true;
      loadMore();
    };
    //搜索书籍
    const fetchBook = useDebounceFn((val: string) => {
      if (val) {
        state.fetching = true;
        landingBook({ book_name: val }).then((res) => {
          let bookList = res.data.list;
          state.bookList = bookList;
          state.fetching = false;
        });
      }
    }, 800);
    const onFileChange = async (file: { file: File }) => {
      if (file.file.size / 1024 > 600)
        return message.error("图片大小超过600KB，请重新选择");
      try {
        let tempFile = file.file;
        const { data } = await onUpload(tempFile, "customTop");
        let url = data.url;
        await landingSaveMypic(url);
        message.success("上传我的图片成功！");
      } catch (error) {
        message.error(error.msg ?? "系统错误");
      }
    };
    //落地页
    const importTemp = () => {
      console.log(state.bookId);
      let errors = 0;
      let content: Array<any> = [];
      if (!state.bookId || !state.charptId) {
        message.error("请选择书籍或者章节");
        errors++;
      }
      if (!state.chooseImgUrl) {
        message.error("头像不能为空");
        errors++;
      }
      if (state.templateItemChecked && !state.templateItemChecked.id) {
        message.error("模板不能为空");
        errors++;
      }
      if (errors > 0) {
        return false;
      }
      const data = {
        head_img: state.chooseImgUrl,
        body_template_id: state.templateItemChecked.id,
        bid: state.bookId,
        sequence: state.charptId,
      };
      let landData = { ...state.stepOneTem, ...data };
      setLandingBook(landData).then((res) => {
        let html = res.data.html_raw;
        state.mycontent = html;
      });
    };
    const uploadMyPic = () => {};
    //选择章节
    const selectBook = useDebounceFn((val: string) => {
      if (val) {
        landingCharpter({ bid: val }).then((res) => {
          state.charptList = res.data;
        });
      }
    }, 500);
    //选择图片
    const chooseImg = (item: any, idx: number) => {
      state.temItem = item;
      state.temChecked = idx;
    };

    //模板列表
    const getTemList = () => {
      getLandingTempalte().then((res: any) => {
        state.templateList = res.data.list;
        //  之前的回显条件&& route.query && route.query.id
        if (props && (props as any).content) {
          const {
            content,
            body_template_id,
            bid,
            book_name,
            head_img,
            html_raw,
            sequence,
          } = (props as any).content;
          try {
            state.charptList = content
              ? JSON.parse(content)
              : [{ title: "", content: "" }];
            state.chooseImgUrl = head_img ?? "";
            state.selectImg = head_img ? true : false;
            if (!body_template_id) return;
            state.templateChecked = state.templateList.findIndex(
              (item) => item.id == body_template_id
            );
            state.bookId = bid;
            state.bookList = [{ bid: bid, book_name: book_name }];
            state.charptId = sequence;
            state.mycontent = html_raw;
            landingCharpter({ bid }).then((res) => {
              state.charptList = res.data;
            });
            state.templateItemChecked =
              state.templateList[state.templateChecked];
          } catch (e) {
            console.log(e);
          }
        }
      });
    };

    //选择正文模板
    const chooseTemplate = (item: any, index: number) => {
      state.templateItemChecked = item;
      console.log(state.templateItemChecked);
      state.templateChecked = index;
    };
    //加载更多
    const loadMore = (page?: number, clear?: boolean) => {
      if (clear) {
        state.temItem = {};
        state.temChecked = null;
        state.dataList = [];
      }
      if (state.activeKey != "14") {
        getLandingPic(
          state.activeKey,
          state.chooseType,
          page ?? state.currentPage
        ).then((res: any) => {
          state.dataList = state.dataList.concat(res.data.list);
          state.currentPage = res.data.meta.current_page + 1;
          if (res.data.meta.is_end) state.showLoaderMore = false;
        });
      } else {
        landingMypic({ page: page ? page : state.currentPage }).then(
          (res: any) => {
            state.dataList = state.dataList.concat(res.data.list);
            state.currentPage = res.data.meta.current_page + 1;
            if (res.data.meta.is_end) state.showLoaderMore = false;
          }
        );
      }
    };
    //选择顶部图
    const handleSumbit = () => {
      state.chooseImgUrl = state.temItem.link;
      state.selectImg = true;
      state.modelShow = false;
    };
    //上一步
    const goPrev = () => {
      let content: Array<any> = [];
      state.charptList.map((r: any) => {
        let item = {
          title: r.title,
          content: r.content,
        };
        content.push(item);
        return r;
      });
      const data = {
        head_img: state.chooseImgUrl,
        body_template_id: state.templateItemChecked.id,
        content: JSON.stringify(content),
      };
      emit("prev", data);
    };
    //保存表单
    const submitForm = () => {
      let errors = 0;
      let content: Array<any> = [];
      if (!state.bookId || !state.charptId) {
        message.error("请选择书籍或者章节");
        errors++;
      }
      if (!state.chooseImgUrl) {
        message.error("头像不能为空");
        errors++;
      }
      if (state.templateItemChecked && !state.templateItemChecked.id) {
        message.error("模板不能为空");
        errors++;
      }
      if (!state.mycontent) {
        message.error("请先导入生成落地页模板");
        errors++;
      }
      if (errors > 0) {
        return false;
      }
      const data = {
        head_img: state.chooseImgUrl,
        body_template_id: state.templateItemChecked.id,
        bid: state.bookId,
        sequence: state.charptId,
        html_raw: state.mycontent,
      };
      let landData = { ...state.stepOneTem, ...data };
      emit("next", landData);
    };

    onMounted(() => {
      getTemList();
    });
    return {
      ...toRefs(state),
      addNewCharpt,
      deleteLine,
      handleSumbit,
      showModel,
      loadMore,
      chooseImg,
      chooseTemplate,
      goPrev,
      submitForm,
      fetchBook,
      selectBook,
      importTemp,
      uploadMyPic,
      onFileChange,
    };
  },
});

export default StepTwo;
</script>
<style lang="scss" scoped>
.button-form {
  margin-left: 120px;
}
.loadmore-list {
  margin-top: 30px;
  .img-item {
    width: 144px;
    height: 144px;
    background: #ffffff;
    border-radius: 6px;
    overflow: hidden;
    position: relative;

    &.current {
      border: 2px solid #006eff;
      &::after {
        position: absolute;
        width: 0;
        height: 0;
        border-top: 20px solid #006eff;
        border-left: 20px solid transparent;
        display: block;
        content: "";
        top: 0;
        right: 0;
      }
    }
  }
}
.template-list {
  width: 726px;
  height: 366px;
  background: #f7f7f7;
  max-height: 366px;
  overflow-y: scroll;
  position: relative;
  padding: 24px 110px;
  .template-item {
    margin: 25px 0;
    background: #fff;
    position: relative;
    &.current {
      border-radius: 6px;
      border: 2px solid #006eff;
      &::after {
        display: block;
        content: "";
        position: absolute;
        right: 8px;
        top: 8px;
        width: 20px;
        height: 20px;
        z-index: 10;
        background-image: url("../../../../assets/checked.png");
        background-repeat: no-repeat;
        background-size: cover;
      }
    }
  }
}
.choose-img {
  .img {
    width: 144px;
    height: 144px;
    overflow: hidden;
    line-height: 144px;
    image {
      display: inline-block;
      vertical-align: middle;
      line-height: initial;
    }
  }
}
.radio-grouped {
  text-align: center;
}
.edit-form {
  .add-item {
    width: 270px;
    height: 40px;
    line-height: 35px;
    color: #006eff;
    font-size: 14px;
    text-align: center;
    background: #ffffff;
    border-radius: 3px;
    border: 2px solid #006eff;
    margin: 15px auto 0;
  }
  .edit-form-item {
    font-size: 14px;
    display: flex;
    align-items: center;
    margin-bottom: 40px;
    .black-chos {
      background-color: #f7f7f7;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
      color: #d8d8d8;
    }
    hr {
      margin-bottom: 25px;
      border: none;
      height: 1px;
      background-color: #e5e5e5;
    }
    .edit-label {
      margin-right: 15px;
      width: 100px;
    }
    .form-content {
      padding: 30px 50px;
      background: #f7f7f7;
    }

    .charpt-list-item {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      overflow: hidden;
      &.bor-line {
        margin-bottom: 25px;
      }
      .item-label {
        margin-right: 18px;
      }
      .delete-text {
        display: block;
        margin-left: 15px;
      }
    }
  }
}
</style>
<style lang="scss">
.bor-line {
  .item-input {
    textarea {
      width: 638px;
    }
  }
}
</style>
