<template>
    <div class="edit-carousel">
      <el-form ref="form" :model="form" label-width="180px">
        <el-form-item label="所属项目：">
          <el-select v-model="form.buildingId" placeholder="请选择">
            <el-option
                    v-for="item in buildingList"
                    :key="item.buildingId"
                    :label="item.buildingName"
                    :value="item.buildingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主图：">
          <el-upload
                  class="avatar-uploader"
                  :headers="uploadHeaders"
                  :action="upFileUrl"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="发布位置：">
          <el-select v-model="form.showPosition" placeholder="请选择">
            <el-option v-for="(item,i) in showPositionList" :key="i" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型：">
          <el-select v-model="form.contentType" placeholder="请选择">
            <el-option v-for="(t,i) in contentTypeList" :key="i" :label="t.name" :value="t.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布内容：" v-if=" form.contentType === 'other'">
          <rich-editor v-model="form.content" style="height: 400px; width: 1000px;" />
        </el-form-item>
        <el-form-item label="发布活动：" class="publish" v-if=" form.contentType === 'activity'">
          <p>{{ showPlace }}<span class="choose" @click="showDial">请选择</span></p>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option v-for="(t,i) in extendContentStatus" :key="i" :label="t.name" :value="t.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddOrUpdate">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>


        <el-dialog title="选择活动" :visible.sync="dialogTableVisible">
          <el-table :data="activityList">
            <el-table-column property="title" label="活动名称"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="handleDel(scope.row)" size="small">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
                  @size-change="dialogHandleSizeChange"
                  @current-change="dialogHandleCurrentChange"
                  :current-page.sync="activityForm.pageNum"
                  :page-size="activityForm.pageSize"
                  layout="total, prev, pager, next"
                  :total="activityTotal">
          </el-pagination>
        </el-dialog>
      </el-form>
    </div>    
</template>

<script>
import { createNamespacedHelpers } from "vuex";
import apis from "../../config/api";
import { mapState } from "vuex";
import E from "wangeditor";

const {
  mapState: mapBuildingState,
  mapActions: mapBuildingActions,
  mapMutations: mapBuildingMutations
} = createNamespacedHelpers("building");

const { mapActions: mapApartmentActions } = createNamespacedHelpers(
  "apartment"
);

const { mapActions: mapImgActions } = createNamespacedHelpers("img");

export default {
  data() {
    var _self = this;
    return {
      form: {
        contentId: '',
        buildingId: '',
        image: '',
        title: '',
        showPosition: '',
        contentType: '',
        content: '',
        status: 0,
        targetId: '',
        showType: 'banner'
      },
      imageUrl: '',
      buildingList: [], // 所属项目
      buildingForm: { // 所属项目条件
        pageNum: 1,
        pageSize: 100
      },
      showPositionList: [
        {
          name: '首页',
          value: 'index'
        },
        {
          name: '商城',
          value: 'mall'
        }
      ],
      contentTypeList: [
        {
          name: '活动',
          value: 'activity'
        },
        {
          name: '项目',
          value: 'project'
        },
        {
          name: '资讯',
          value: 'news'
        },
        {
          name: '其他',
          value: 'other'
        }
      ],
      extendContentStatus: [ // 状态
        {
          name: "启用",
          value: 1
        },
        {
          name: "停用",
          value: 0
        },
      ],
      activityForm: { // 活动查询条件
        pageNum: 1,
        pageSize: 10
      },
      activityTotal: 0, // 活动总数
      dialogTableVisible: false, //选择活动弹框
      activityList: [], // 活动列表






      // 下面的不敢删除
      popover4:false,//弹框
      showPlace:'',//活动名称展示处
      gridData: [
        {
          date: "2016-05-02",
          name: "高奢生活，在遇到它之前你想象不到"
        },
        {
          date: "2016-05-04",
          name: "欢乐套圈圈，福利大放送"
        },
        {
          date: "2016-05-01",
          name: "上海市普陀区金沙江路 1518 弄"
        }
      ],
      upFileUrl: apis.file.upload.url,
      commPrefix: "",
      imgurl: "",
      loadingZm: false,
      activeName: "detail",
      dialogImageUrl: "",
      dialogVisible: false,
      dialogApartImageUrl: "",
      dialogApartVisible: false,
      showHx: false,
      imgList: [],
      tags: [],
      buildingProperty: [],
      aparments: [],
      aparmentInfo: {},
      aparmentImg: [],
      saleType: [
        {
          id: 1,
          name: "待定"
        },
        {
          id: 2,
          name: "售罄"
        },
        {
          id: 3,
          name: "在售"
        }
      ]
    };
  },
  computed: {
    ...mapBuildingState({
      detail: x => x.detail
    }),
    ...mapState({
      dicts: x => x.dicts
    }),
    building: {
      get() {
        return this.detail;
      },
      set(val) {
        return this.updateDetail(val);
      }
    },
    propertyType() {
      return (this.dicts || []).filter(x => x.type === "propertyType");
    },
    uploadHeaders() {
      const token = localStorage.getItem("x-token") || "";
      return {
        Authorization: `Bearer ${token}`
      };
    }
  },
  methods: {
    ...mapBuildingMutations(["updateDetail"]),
    ...mapBuildingActions(["getDetail", "addBuilding", "editBuilding"]),
    ...mapApartmentActions([
      "getApartments",
      "getApartmentDetail",
      "addApartment",
      "editApartment",
      "deleteApartment"
    ]),
    ...mapImgActions(["uploadImg"]),
    getSaleTypeName(id) {
      return (this.saleType.filter(x => x.id == id)[0] || {}).name;
    },
    onCancel() {
      this.$router.go(-1)
    },
    handleRemove(file, fileList) {
      this.imgList = fileList;
    },
    handleAparmentRemove(file, fileList) {
      this.aparmentImg = fileList;
    },

    beforeImgUpload(file) {
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      // if (file.size / 1024 > 300) {
      //   this.$message.error('图片大小不允许超过300k!')
      //   return false
      // }
      this.loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      return true;
    },
    handleAvatarSuccess(res) {
      this.imageUrl = res.data
      this.form.image = res.data
    },
    handleMapImgSuccess(res) {
      this.building = { ...this.building, mapImg: res.data };
      this.loading.close();
    },
    handlePosterSuccess(res) {
      this.building = { ...this.building, poster: res.data };
      this.loading.close();
    },
    handleAparmentSuccess(res) {
      this.aparmentImg = [
        ...this.aparmentImg,
        {
          url: res.data
        }
      ];
      this.loading.close();
    },
    onSubmit() {
      const imgs = this.imgList.map((x, i) => {
        return {
          imgType: "banner",
          url: x.url,
          orderNo: i + 1
        };
      });
      const tag = this.tags.map(x => {
        return {
          tagName: x
        };
      });
      const building = {
        ...this.building,
        img: imgs,
        propertyType: this.buildingProperty.join(","),
        tag
      };
      if (!building.buildingId) {
        // 新增
        this.addBuilding({
          onSuccess: this.onCancel,
          detail: JSON.stringify(building)
        });
      } else {
        // 修改
        this.editBuilding({
          onSuccess: this.onCancel,
          detail: JSON.stringify(building)
        });
      }
    },
    FormatDate(date) {
      return (date || "").split("T")[0] === "0001-01-01"
        ? ""
        : (date || "").split("T")[0];
    },
    saveAparment() {
      const imgs = this.aparmentImg.map((x, i) => {
        return {
          imgType: "aparment",
          url: x.url,
          orderNo: i + 1
        };
      });
      if (!this.aparmentInfo.apartmentId) {
        this.addApartment(
          JSON.stringify({
            ...this.aparmentInfo,
            img: imgs
          })
        ).then(() => {
          this.getAparmentList();
          this.showHx = false;
        });
      } else {
        this.editApartment(
          JSON.stringify({
            ...this.aparmentInfo,
            img: imgs
          })
        ).then(() => {
          this.getAparmentList();
          this.showHx = false;
        });
      }
    },
    addHx() {
      this.aparmentImg = [];
      this.aparmentInfo = { buildingId: this.building.buildingId };
      this.showHx = true;
    },
    getAparmentList() {
      this.getApartments({ buildingId: this.$route.query.id }).then(data => {
        this.aparments = data;
      });
    },
    handleEdit(row){
      this.showPlace = row.name
      this.popover4 = false


    },
    // handleEdit(row) {
    //   this.aparmentImg = [];
    //   this.getApartmentDetail({
    //     id: row.apartmentId
    //   }).then(data => {
    //     console.log("...", data);
    //     this.aparmentImg = data.buildingImgList.map(x => {
    //       return {
    //         name: x.imgId,
    //         url: x.url
    //       };
    //     });
    //     this.aparmentInfo = data;
    //     this.showHx = true;
    //   });
    // },
    handleDel(row) { // 选择
      this.form.targetId = row.dynamicId
      this.showPlace = row.title
      this.dialogTableVisible = false
    },

    showDial() { // 显示活动弹窗
      this.dialogTableVisible = true
      this.getActivityList()
    },
    getExtendContentById() {
      this.$store.dispatch('carouselFigure/getByIdExtendContent', this.form).then((res) => {
        console.log('carouselFigure/getByIdExtendContent', res)
        this.form = res
        this.imageUrl = res.image
        this.showPlace = res.targetName
      }).catch((err) => {
        this.$notify.error(err.msg || err.message);
        console.log('carouselFigure/getByIdExtendContent err')
      })
    },
    getBuildList() {
      this.$store.dispatch('building/getBuildings', this.buildingForm).then((res) => {
        this.buildingList = res.records
      }).catch((err) => {
        this.$notify.error(err.msg || err.message);
        console.log('building/getBuildings err')
      })
    },
    getActivityList() { // 活动列表
      this.$store.dispatch('activity/getActivityList',this.activityForm).then(res => {
        this.activityList = res.list;
        this.activityForm.pageSize = res.pageSize
        this.activityForm.pageNum = res.pageNum
        this.activityTotal = res.total
      }).catch(err => {
        this.$notify.error(err.msg || err.message);
      });
    },
    dialogHandleSizeChange(value) {
      this.activityForm.pageSize = value
      this.getActivityList()
    },
    dialogHandleCurrentChange(value) {
      this.activityForm.pageNum = value
      this.getActivityList()
    },
    submitAddOrUpdate() { // 添加或者修改

      // 添加
      if (this.form.contentId === undefined || this.form.contentId === '') {
        this.$store.dispatch('carouselFigure/addExtendContent', this.form).then((res) => {
          this.$message.success('操作成功')
          this.$router.go(-1)
        }).catch((err) => {
          this.$notify.error(err.msg || err.message);
        })
        return
      }

      // 修改
      this.$store.dispatch('carouselFigure/updateExtendContent', this.form).then((res) => {
        this.$message.success('操作成功')
        this.$router.go(-1)
      }).catch((err) => {
        this.$notify.error(err.msg || err.message);
        console.log('carouselFigure/updateExtendContent err')
      })
    },

  },
  created() {
    this.form.contentId = this.$route.query.id
    if (this.$route.query.id !== undefined) {
      this.getExtendContentById()
    }
    this.getBuildList()
  }
};
</script>

<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>

<style lang="scss" scoped>
.header {
  width: 50px;
  height: 50px;
  img {
    width: 100%;
    height: 100%;
  }
}
.edit-carousel {
  .el-select {
    max-width: 300px !important;
  }
  .el-input {
    max-width: 400px;
  }
  .publish {
    p {
      margin: 0;
      font-size: 15.4px;
      .choose {
        color: blue;
        margin-left: 15px;
      }
    }
  }
}
.el-popover {
  z-index: 10004 !important;
  .el-table .cell{
    text-align: center;
  }
}

.el-select-dropdown {
  z-index: 10003 !important;
}

.el-date-picker {
  z-index: 10002 !important;
}
</style>
