<template>
  <div>
    <xy-dialog
      ref="dialog"
      :width="74"
      type="form"
      :is-show.sync="isShow"
      :title="this.type === 'add' ? '新增产品' : '编辑产品'"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >产品名称：
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.name"
              placeholder="请输入名称"
              clearable
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>

      <template v-slot:confinementServicesId>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >所属机构：
          </div>
          <div class="xy-table-item-content">
            <el-select
              clearable
              v-model="form.confinementServicesId"
              style="width: 300px"
              placeholder="请选择所属机构"
            >
              <Scroll :on-reach-bottom="loadMoreClub">
                <el-option
                  v-for="item in clubs"
                  :value="item.id"
                  :key="item.id"
                  :label="item.name"
                >
                </el-option>
              </Scroll>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:state>
        <div class="xy-table-item">
          <div class="xy-table-item-label">是否启用：</div>
          <div class="xy-table-item-content">
            <el-switch v-model="form.state" type="primary"></el-switch>
          </div>
        </div>
      </template>

      <template v-slot:recommend>
        <div class="xy-table-item">
          <div class="xy-table-item-label">是否推荐主页：</div>
          <div class="xy-table-item-content">
            <el-switch v-model="form.recommend" type="primary"></el-switch>
          </div>
        </div>
      </template>

      <template v-slot:sortNumber>
        <div class="xy-table-item">
          <div class="xy-table-item-label">排序：</div>
          <div class="xy-table-item-content">
            <el-input-number
              :precision="0"
              :controls="false"
              v-model="form.sortNumber"
              placeholder="请输入排序"
              clearable
              style="width: 300px"
            ></el-input-number>
          </div>
        </div>
      </template>

      <template v-slot:video>
        <div class="xy-table-item">
          <div class="xy-table-item-label">宣传视频：</div>
          <div class="xy-table-item-content">
            <div v-if="form.video" style="position: relative">
              <video :src="form.video" class="avatar" />
              <Button
                shape="circle"
                icon="md-close"
                type="error"
                size="small"
                class="img__delete"
                @click="form.video = ''"
              ></Button>
            </div>
            <el-upload
              v-else
              :limit="1"
              accept="video/*"
              class="avatar-uploader"
              list-type="picture-card"
              :action="action"
              :show-file-list="true"
              :on-error="uploadFailVideo"
              :on-success="uploadSuccessVideo"
              :before-upload="uploadBeforeVideo"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>

      <template v-slot:featuredLabel>
        <div class="xy-table-item">
          <div class="xy-table-item-label">特色标签：</div>
          <div class="xy-table-item-content">
            <div class="xy-table-item-content-label">
              <template v-for="(item, index) in form.featuredLabel">
                <el-tag
                  type="primary"
                  closable
                  @close="labelClose(index)"
                  style="margin-right: 6px; margin-bottom: 4px"
                  >{{ item }}</el-tag
                >
              </template>
              <div style="margin-top: 15px">
                <el-input
                  clearable
                  placeholder="请填写并添加特色标签"
                  style="width: 300px"
                  ref="labelInput"
                  v-model="labelText"
                >
                  <el-button
                    type="primary"
                    slot="append"
                    icon="el-icon-plus"
                    @click="appendLabel"
                  ></el-button>
                </el-input>
              </div>
            </div>
          </div>
        </div>
      </template>

      <template v-slot:price>
        <div class="xy-table-item">
          <div class="xy-table-item-label">价格：</div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input-number
              :precision="2"
              :controls="false"
              v-model="form.price"
              placeholder="请输入价格"
              clearable
              style="width: 300px"
            ></el-input-number>
          </div>
        </div>
      </template>

      <template v-slot:coverPicture>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >封面图：
          </div>
          <div class="xy-table-item-content xy-table-item-content-cover">
            <div v-if="form.coverPicture" style="position: relative">
              <img :src="form.coverPicture" class="avatar" />
              <Button
                shape="circle"
                icon="md-close"
                type="error"
                size="small"
                class="img__delete"
                @click="form.coverPicture = ''"
              ></Button>
            </div>
            <el-upload
              v-else
              accept="picture"
              :limit="1"
              class="avatar-uploader"
              list-type="picture-card"
              :action="action"
              :show-file-list="true"
              :on-error="uploadFailPic"
              :on-success="uploadSuccessPic"
              :before-upload="uploadBeforePic"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>

      <template v-slot:timeLimit>
        <div class="xy-table-item">
          <div class="xy-table-item-label">限时：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              clearable
              style="width: 440px"
              v-model="form.timeLimit"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >内容：
          </div>
          <div class="xy-table-item-content" style="width: 680px">
            <!-- <xy-tinymce v-model="form.content"></xy-tinymce> -->
			<xyTinymce v-if="isShow" :height="200" v-model="form.content"></xyTinymce>
          </div>
        </div>
      </template>

      <template v-slot:set_list>
        <div class="xy-table-item">
          <div class="xy-table-item-label">明细：</div>
          <div class="xy-table-item-content">
            <Button
              type="primary"
              icon="md-add"
              @click="addListCombo"
              style="margin-bottom: 10px"
              >新增</Button
            >

            <xy-table
              :height="260"
              :is-page="false"
              :list="form.set_list"
              :table-item="tableCombo"
            >
              <template v-slot:btns>
                <el-table-column
                  label="操作"
                  width="90"
                  header-align="center"
                  align="center"
                >
                  <template slot-scope="scope">
                    <Button
                      size="small"
                      type="primary"
                      ghost
                      @click="deleteCombo(scope)"
                      >删除</Button
                    >
                  </template>
                </el-table-column>
              </template>
            </xy-table>
          </div>
        </div>
      </template>

      <template v-slot:picture_list>
        <div class="xy-table-item">
          <div class="xy-table-item-label">图集：</div>
          <div class="xy-table-item-content">
            <el-upload
              class="upload-demo"
              :action="action"
              :before-upload="uploadBeforePic"
              :on-success="picListSuccessHandler"
              :on-remove="picListRemoveHandler"
              :file-list="picfileList"
              list-type="picture"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件或者视频文件，且不超过10M
              </div>
            </el-upload>
          </div>
        </div>
      </template>
    </xy-dialog>
  </div>
</template>

<script>
import {
  store,
  show,
  save,
  getPicture,
  getCombo,
} from "@/api/productService/commonServiceProduct";
import { index as clubIndex } from "@/api/productService/commonService";
import { getparameter } from "@/api/system/dictionary";
import { Message } from "element-ui";

import xyTinymce from "@/components/XyTinymce/index.vue";
    import {replaceAll} from "@/utils/index"
export default {
  components: {
    xyTinymce,
  },
  data() {
    return {
      picfileList: [],
      id: "",
      isShow: false,
      type: "",
      listCombo: [],
      tableCombo: [
        {
          label: "名称",
          sortable: false,
          minWidth: 220,
          customFn: (row) => {
            return (
              <div>
                <el-input
                  size="small"
                  placeholder="请输入名称"
                  value={row.name}
                  on={{
                    ["input"]: (e) => {
                      row.name = e;
                    },
                  }}
                />{" "}
              </div>
            );
          },
        },
        {
          label: "内容",
          sortable: false,
          minWidth: 420,
          customFn: (row) => {
            return (
              <div>
                <el-input
                  size="small"
                  placeholder="请输入内容"
                  value={row.content}
                  on={{
                    ["input"]: (e) => {
                      row.content = e;
                    },
                  }}
                />{" "}
              </div>
            );
          },
        },
      ],

      action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
      clubSelect: {
        pageSize: 10,
        page: 1,
        type: "maternity",
      },
      clubs: [],
      roomTypes: [],
      equips: [],
      labelText: "",
      form: {
        name: "",
        confinementServicesId: "", //所属机构
        sortNumber: 0,
        featuredLabel: [],
        state: true,
        price: 0,
        recommend: false,
        coverPicture: "",
        timeLimit: "",
        content: "",
        video: "",
        set_list: [],
        picture_list: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: "请填写产品名称",
          },
        ],
        confinementServicesId: [
          {
            required: true,
            message: "请选择所属机构",
          },
        ],
        coverPicture: [
          {
            required: true,
            message: "请上传封面图",
          },
        ],
        content: [
          {
            required: true,
            message: "请填写内容",
          },
        ],
      },
    };
  },
  methods: {
    init(){
      this.picfileList = []
      this.form = {
        name: "",
        confinementServicesId: "", //所属机构
        sortNumber: 0,
        featuredLabel: [],
        state: true,
        price: 0,
        recommend: false,
        coverPicture: "",
        timeLimit: "",
        content: "",
        video: "",
        set_list: [],
        picture_list: [],
      }
    },

    addListCombo() {
      this.form.set_list.push({
        name: "",
        content: "",
      });
    },

    deleteCombo(scope) {
      this.form.set_list.splice(scope.$index, 1);
    },
    //上传
    picListSuccessHandler(res, file, fileList) {
      this.form.picture_list = fileList.map((item) => {
        return item.response
          ? {
            picture: item.response.url,
            type: 0,
          }
          : {
            picture: item.url,
            type: 0,
          };
      });
    },
    picListRemoveHandler(file, fileList) {
      this.form.picture_list = fileList.map((item) => {
        return item.response
          ? {
            picture: item.response.url,
            type: 0,
          }
          : {
            picture: item.url,
            type: 0,
          };
      });
    },
    uploadFailVideo(err) {
      console.log(err);
    },
    uploadSuccessVideo(response) {
      console.log(response);
      this.form.video = response.url;
    },
    uploadBeforeVideo(file) {
      if (file.size / 1000 > 10240) {
        Message({
          type: "warning",
          message: "上传视频大小超过10M！",
        });
        return false;
      }
    },
    uploadFailPic(err) {
      console.log(err);
    },
    uploadSuccessPic(response) {
      console.log(response);
      this.form.coverPicture = response.url;
    },
    uploadBeforePic(file) {
      if (file.size / 1000 > 2048) {
        Message({
          type: "warning",
          message: "上传图片大小超过2M！",
        });
        return false;
      }
    },

    //特色标签添加
    appendLabel() {
      if (!this.$refs["labelInput"].getInput().value) return;
      this.form.featuredLabel.push(this.$refs["labelInput"].getInput().value);
      this.labelText = "";
    },
    //特色标签删除
    labelClose(index) {
      this.form.featuredLabel.splice(index, 1);
    },

    async getRoomTypes() {
      const res = await getparameter({
        number: "confinementRoomType",
      });
      this.roomTypes = res.detail;
    },

    async getClubs() {
      const res = await clubIndex(
        {
          page: this.clubSelect.page,
          page_size: this.clubSelect.pageSize,
          type: this.clubSelect.type,
        },
        false
      );
      if (res?.data?.length === 0) {
        this.$Message.info({
          content: "没有更多了",
          duration: 1,
        });
        this.clubSelect.page--;
      }
      this.clubs.push(...res.data);
    },

    async getEquips() {
      const res = await getparameter({
        number: "confinementEquip",
      });
      this.equips = res.detail;
    },

    async getDetail() {
      const res = await show({
        id: this.id,
      });
      console.log(res);
      this.form = {
        name: res?.name,
        confinementServicesId: res?.common_services_id, //所属机构
        roomType: res?.room_type,
        sortNumber: res?.sort_number,
        featuredLabel: res?.featured_label?.split(",") || [], //特色标签
        roomOrientation: res?.room_orientation, //房间朝向
        roomFacility:
          res?.room_facility?.split(",").map((item) => Number(item)) || [], //房间设施
        roomArea: res?.room_area,
        price: res?.price,
        state: !!res?.state,
        recommend: !!res?.recommend,
        coverPicture: res?.cover_picture,
        timeLimit: res?.time_limit?.split(","),
        content: res?.content,
        video: res?.video,
        set_list: res?.set.map((item) => {
          return {
            name: item.name,
            content: item.content,
          };
        }),
        picture_list: [],
      };
      this.picfileList = res?.picture.map((item) => {
        return {
          url: item.picture,
          name: item.created_at,
        };
      });
    },

    loadMoreClub() {
      this.clubSelect.page++;
      this.getClubs();
    },
    submit() {
      let _form = {
        name: this.form.name,
        room_type: this.form.roomType,
        common_services_id: this.form.confinementServicesId,
        state: this.form.state ? 1 : 0,
        sort_number: this.form.sortNumber,
        featured_label: this.form.featuredLabel?.toString(),
        // content: this.form.content,
        recommend: this.form.recommend ? 1 : 0,
        room_orientation: this.form.roomOrientation,
        cover_picture: this.form.coverPicture,
        room_facility: this.form.roomFacility?.toString(),
        price: this.form.price,
        room_area: this.form.roomArea,
        time_limit: this.form.timeLimit?.toString(),
        video: this.form.video,
        set_list: this.form.set_list,
        picture_list: this.form.picture_list,
		content: replaceAll(this.form.content,'../storage/files',`${process.env.VUE_APP_BASE_API}storage/files`)
		
      };
      if (this.type === "add") {
        store(_form).then((res) => {
          Message({
            type: "success",
            message: "新增产品成功",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      } else if (this.type === "editor") {
        save({
          id: this.id,
          ..._form,
        }).then((res) => {
          Message({
            type: "success",
            message: "编辑产品成功",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      }
    },
  },
  watch: {
    isShow(newVal) {
      if (newVal) {
        this.getClubs();

        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.id = "";
        this.type = "";
        this.clubs = [];
        this.clubSelect.page = 1;
        this.init()
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .ivu-select-dropdown {
}

::v-deep .ivu-scroll-container {
  height: 140px !important;

  &::after {
    content: "加载更多..";
    text-align: center;
    font-size: 10px;
    zoom: 0.8;
    color: rgb(160, 160, 160);
    background: #fff;

    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
  }
}

.xy-table-item {
  &-label {
    width: 160px;
  }

  &-content {
    &-label {
      width: 300px;
      display: flex;
      flex-wrap: wrap;
      flex: 0;
    }
  }

  &-content-cover {
    position: relative;

    &::after {
      font-size: 10px;
      white-space: nowrap;
      word-break: keep-all;
      content: "建议尺寸 800*450";
      zoom: 0.84;

      position: absolute;
      bottom: -34px;
      right: 4px;
    }
  }

  &-area {
    position: relative;

    &::after {
      z-index: 1;
      position: absolute;
      right: 0;
      top: 0;
      content: "（平方米）";
    }

    ::v-deep .el-input__clear {
      position: relative;
      right: 30px;
      z-index: 2;
    }
  }
}

::v-deep .el-input__inner {
  text-align: left;
}
</style>
<style>
.avatar-uploader .el-upload {
  width: 110px;
  height: 110px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #bf617c;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  line-height: 110px;
  text-align: center;
}

.avatar {
  width: 110px;
  display: block;
  border-radius: 6px;
}

.img__delete {
  transform: scale(0.7, 0.7);

  position: absolute;
  top: 1px;
  left: 4%;
}
</style>
