<template>
  <div>
    <el-tabs type="border-card" >
    <el-tab-pane label="基本信息">
    <el-form ref="form" :model="building" label-width="160px">
      <el-form-item label="项目名称：" >
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="项目简称：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="项目类型：">
        <el-select v-model="building.buildingId" placeholder="请选择">
          <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目编码：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="项目区域：">
        <el-select v-model="building.buildingId" placeholder="请选择">
          <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="均价：">
        <el-input v-model="building.desc"></el-input> &nbsp;元/m²
      </el-form-item>
      <el-form-item label="开盘日期：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="物业类型：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="项目电话：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="项目联系人：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="销售状态：">
        <el-select v-model="building.buildingId" placeholder="请选择">
          <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间：">
        <el-input v-model="building.desc"></el-input>
      </el-form-item>
      <el-form-item label="项目标签：">
        <el-input v-model="building.desc" placeholder="(输入标签后按回车生成)" ></el-input>
      </el-form-item>
      <el-form-item label="首页推荐：">
        <template>
          <el-radio v-model="radio" label="1">是</el-radio>
          <el-radio v-model="radio" label="2">否</el-radio>
        </template>
      </el-form-item>   
      <el-form-item label="项目状态：">
        <el-select v-model="building.buildingId" placeholder="请选择">
          <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-tab-pane>

  <el-tab-pane label="交通及周边设施">
    <el-form ref="form" :model="building" label-width="160px">
     <el-form-item label="项目地图图片：">
        <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList1"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess1"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl1" alt="">
          </el-dialog>
      </el-form-item>
      <el-form-item label="项目地址：">
        <el-input v-model="building.desc" ></el-input>
      </el-form-item> 
      <el-form-item label="项目经纬度：">
          <div class="search">
            <!-- <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box> -->
           <el-input v-model="building.desc" placeholder="按关键词搜索" ></el-input>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
           <el-input v-model="building.desc" placeholder="左击获取经纬度" ></el-input>
          </div>
          <div class="flex-item">
            <div style="width: 100%;">
              <el-amap ref="map" vid="amapDemo" :center="mapCenter" :zoom="12" :events="events" class="amap-demo">
                <el-amap-marker v-for="(item,index) in markers" :key="index" :position="item" ></el-amap-marker>
              </el-amap>
            </div>
          </div>  
        </el-form-item>
      <el-form-item label="周边设施:">
        <div id="websiteEditorElem" style="height: 400px"></div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
      </el-form>  
  </el-tab-pane>
  <el-tab-pane label="户型相册">
    <el-form ref="form" :model="building" label-width="150px">
      <p class="title">户型:</p>
      <div v-for="(item,index) in 2" :key="index" class="apartment-box">
        <el-form-item label="户型图：">
          <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList2"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess2"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl2" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="building.desc" ></el-input>
        </el-form-item>
        <el-form-item label="面积：">
          <el-input v-model="building.desc" ></el-input> &nbsp;m²
        </el-form-item>
        <el-form-item label="套内面积：">
          <el-input v-model="building.desc" ></el-input> &nbsp;m²
        </el-form-item>
        <el-form-item label="销售状态：">
        <el-select v-model="building.buildingId" placeholder="请选择">
          <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
        </el-select>
        <el-button type="warning" @click="onSubmit">删除</el-button>
      </el-form-item>
        <el-form-item label="总价：">
          <el-input v-model="building.desc" ></el-input> &nbsp;万
        </el-form-item>
        <el-form-item label="简介：">
          <el-input type="textarea" :rows="5"  v-model="building.desc"></el-input>
        </el-form-item>
    </div>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">添加户型</el-button>
    </el-form-item>
    <p class="title">项目相册:</p>
      <el-form-item label="效果图">
          <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList3"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess3"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl3" alt="">
          </el-dialog>
      </el-form-item>
      <el-form-item label="实景图">
          <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList4"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess4"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl4" alt="">
          </el-dialog>
      </el-form-item>
      <el-form-item label="样板间">
          <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList5"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess5"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl5" alt="">
          </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-tab-pane>

</el-tabs>
  </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 {
      upFileUrl: apis.file.upload.url,
      radio: "1",
      showHx: false,
      dialogVisible: false,
      dialogImageUrl1: "",
      dialogImageUrl2: "",
      dialogImageUrl3: "",
      dialogImageUrl4: "",
      dialogImageUrl5: "",
      markers: [],
      imgList1: [],
      imgList2: [],
      imgList3: [],
      imgList4: [],
      imgList5: [],
      tags: [],
      buildingProperty: [],
      aparments: [],
      aparmentInfo: {},
      aparmentImg: [],
      searchOption: {
        city: "南京",
        citylimit: false
      },
      saleType: [
        {
          id: 1,
          name: "待定"
        },
        {
          id: 2,
          name: "售罄"
        },
        {
          id: 3,
          name: "在售"
        }
      ],
      mapCenter: [118.789509, 32.019989],
      events: {
        click: e => {
          _self.updateDetail({
            ..._self.building,
            coordinate: e.lnglat.lat + "," + e.lnglat.lng
          });
        }
      }
    };
  },
  computed: {
    ...mapBuildingState({
      detail: x => x.detail,
      buildings: x => x.buildings
    }),
    ...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",
      "getBuildings"
    ]),
    ...mapApartmentActions([
      "getApartments",
      "getApartmentDetail",
      "addApartment",
      "editApartment",
      "deleteApartment"
    ]),
    ...mapImgActions(["uploadImg"]),

    getSaleTypeName(id) {
      return (this.saleType.filter(x => x.id == id)[0] || {}).name;
    },
    onCancel() {
      this.$router.push({ name: "buildinglist" });
    },
    handleRemove(file, fileList) {
      this.imgList = fileList;
    },
    handleAparmentRemove(file, fileList) {
      this.aparmentImg = fileList;
    },
    onSearchResult(pois) {
      // 搜索地图
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.markers.push([poi.lng, poi.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.mapCenter = [center.lng, center.lat];
      }
    },
    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;
    },
    handleAvatarSuccess1(res) {
      this.imgList1 = [
        ...this.imgList1,
        {
          url: res.data
        }
      ];
      this.loading.close();
    },
    handleAvatarSuccess2(res) {
      this.imgList2 = [
        ...this.imgList2,
        {
          url: res.data
        }
      ];
      this.loading.close();
    },
    handleAvatarSuccess3(res) {
      this.imgList3 = [
        ...this.imgList3,
        {
          url: res.data
        }
      ];
      this.loading.close();
    },
    handleAvatarSuccess4(res) {
      this.imgList4 = [
        ...this.imgList4,
        {
          url: res.data
        }
      ];
      this.loading.close();
    },
    handleAvatarSuccess5(res) {
      this.imgList5 = [
        ...this.imgList5,
        {
          url: res.data
        }
      ];
      this.loading.close();
    },
    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.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.$confirm("确认删除此数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (this.building.status === 1) {
          this.$message.error("当前楼盘处于发布状态，不允许删除！");
          return false;
        }
        this.deleteApartment({
          id: row.apartmentId
        }).then(() => {
          this.getAparmentList();
        });
      });
    }
  },
  mounted() {
    const _that = this;
    const phoneEditor = new E("#websiteEditorElem");
    phoneEditor.customConfig.onchange = function(html) {
      _that.dynamic = { ..._that.dynamic, url: html };
    };
    // phoneEditor.customConfig.uploadImgServer = this.upFileUrl
    // phoneEditor.customConfig.uploadFileName = 'uploadFiles'

    phoneEditor.customConfig.customUploadImg = function(files, insert) {
      _that.uploadImg(files[0]).then(data => {
        insert(data);
      });
    };
    phoneEditor.customConfig.menus = [
      "head", // 标题
      "bold", // 粗体
      "fontSize", // 字号
      "fontName", // 字体
      "italic", // 斜体
      "underline", // 下划线
      "strikeThrough", // 删除线
      "foreColor", // 文字颜色
      "backColor", // 背景颜色
      "justify", // 对齐方式
      "image", // 插入图片
      "link", // 插入链接
      "list", // 列表
      "quote", // 引用
      "emoticon", // 表情
      "table", // 表格
      "video", // 插入视频
      "code", // 插入代码
      "undo", // 撤销
      "redo" // 重复
    ];
    phoneEditor.create();

    this.getBuildings({
      pageNum: 1,
      pageSize: 100
    }).then(() => {
      if ((this.$route.query.id || "") !== "") {
        this.getDetail({ id: this.$route.query.id }).then(data => {
          phoneEditor.txt.html(data.url);
        });
      }
    });
  }
};
</script>

<style lang="scss">
.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: 160px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}
.avatar {
  width: 160px;
  height: 160px;
  display: block;
}
.el-input {
  max-width: 500px;
}
.search {
  margin-bottom: 20px;
  .el-input {
    max-width: 240px;
  }
  .el-button {
    margin: 0 20px;
  }
}

.flex-item .amap-demo {
  height: 300px;
}
.apartment-box {
  width: 50%;
  padding: 20px 0;
  display: inline-block;
  .el-input {
    max-width: 300px;
  }
  .el-select {
    max-width: 250px !important;
    margin-right: 20px;
  }
}
.title{
  font-size: 20px;
  font-weight: 600;
  color: #000;
  margin: 8px 20px;
}
</style>
