<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="基础信息" name="detail">
      <el-form ref="form" :model="building" label-width="160px" class="building-form">
        <el-form-item label="楼盘编号">
          <el-input v-model="building.code"></el-input>
        </el-form-item>
        <el-form-item label="楼盘名称">
          <el-input v-model="building.buildingName"></el-input>
        </el-form-item>
        <el-form-item label="别名">
          <el-input v-model="building.name"></el-input>
        </el-form-item>
        <el-form-item label="均价">
          <el-input v-model="building.price"></el-input>
        </el-form-item>
        <el-form-item label="开盘时间">
          <el-date-picker
            v-model="building.openingDate"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="building.tel"></el-input>
        </el-form-item>
        <el-form-item label="项目动态">
          <el-input v-model="building.dynamic"></el-input>
        </el-form-item>
        <el-form-item label="物业类型">
          <el-select v-model="buildingProperty" multiple placeholder="请选择">
            <el-option v-for="(t,i) in propertyType" :key="i" :label="t.name" :value="t.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售状态">
          <el-input v-model="building.marketStatus"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入标签">
          </el-select>
        </el-form-item>
        <el-form-item label="项目主图">
          <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="地址图片">
          <el-upload
            class="avatar-uploader"
            :action="upFileUrl"
            :headers="uploadHeaders"
            name='file'
            :show-file-list="false"
            :before-upload="beforeImgUpload"
            :on-success="handleMapImgSuccess">
            <img v-if="building.mapImg" :src="building.mapImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="海报底图">
          <el-upload
            class="avatar-uploader"
            :action="upFileUrl"
            :headers="uploadHeaders"
            name='file'
            :show-file-list="false"
            :before-upload="beforeImgUpload"
            :on-success="handlePosterSuccess">
            <img v-if="building.poster" :src="building.poster" 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="building.orderNo"></el-input>
        </el-form-item>
        <el-form-item label="优惠信息">
          <el-input v-model="building.discount"></el-input>
        </el-form-item>
        <el-form-item label="首页推荐">
          <el-radio-group v-model="building.isMain">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所在城市">
          <el-select v-model="building.cityId" filterable placeholder="请选择">
            <el-option  v-for="(list,i) in cityNameList" :key="i" :label="list.name" :value="list.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼盘区域">
          <el-input v-model="building.buildingArea"></el-input>
        </el-form-item>
        <el-form-item label="项目地址">
          <el-input v-model="building.address"></el-input>
        </el-form-item>
        <el-form-item label="项目坐标">
          <el-input v-model="building.coordinate" :disabled="true"></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>
          </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="周边交通">
          <editable-tag v-model="building.buildingTransport" />
        </el-form-item>
        <el-form-item label="周边商业">
          <editable-tag v-model="building.buildingMall" />
        </el-form-item>
        <el-form-item label="周边学校">
          <editable-tag v-model="building.buildingEdu" />
        </el-form-item>
        <el-form-item label="周边医院">
          <editable-tag v-model="building.buildingHospital" />
        </el-form-item>
        <el-form-item label="周边银行">
          <editable-tag v-model="building.buildingBank" />
        </el-form-item>
        <el-form-item label="周边餐饮">
          <editable-tag v-model="building.buildingRestaurant" />
        </el-form-item>
        <el-form-item label="项目类型">
        </el-form-item>
        <el-form-item label="绿化率">
          <el-input v-model="building.greeningRate"></el-input>
        </el-form-item>
        <el-form-item label="容积率">
          <el-input v-model="building.volumeRate"></el-input>
        </el-form-item>
        <el-form-item label="车位比">
          <el-input v-model="building.parkingRate"></el-input>
        </el-form-item>
        <el-form-item label="规划户数">
          <el-input-number v-model="building.familyNum"></el-input-number>
        </el-form-item>
        <el-form-item label="物业公司">
          <el-input v-model="building.serviceCompany"></el-input>
        </el-form-item>
        <el-form-item label="物业费">
          <el-input v-model="building.serviceFee"></el-input>
        </el-form-item>
        <el-form-item label="装修标准">
          <el-input v-model="building.decoration"></el-input>
        </el-form-item>
        <el-form-item label="交房时间">
          <el-date-picker
            v-model="building.receivedDate"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产权年限">
          <el-input-number v-model="building.rightsYear"></el-input-number>
        </el-form-item>
        <el-form-item label="预售许可证">
          <el-upload
            class="avatar-uploader"
            :action="upFileUrl"
            :headers="uploadHeaders"
            name='file'
            :show-file-list="false"
            :before-upload="beforeImgUpload"
            :on-success="handlePreSalePermitSuccess">
            <img v-if="building.preSalePermit" :src="building.preSalePermit" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目备注">
          <rich-editor v-model="building.remark" style="height: 400px" />
        </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="图片设置" name="apartment" v-if="detail.buildingId">
      <div class="system-table-search">
        <div class="flex-h">
          <div class="flex-item flex-h">
            <el-button size="mini" type="success" @click='addHx'>新增图片库</el-button>
          </div>
        </div>
      </div>
      <el-table
        :data="aparments"
        style="width: 100%">
        <el-table-column
          prop="apartmentName"
          label="名称"
        >
        </el-table-column>
        <el-table-column
          prop="apartmentType"
          label="类型"
        >
          <template slot-scope="scope">
            <span>{{scope.row.apartmentType == 'apart'?'户型':'相册'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="marketStatus"
          label="销售状态"
        >
          <template slot-scope="scope">
            <span>{{getSaleTypeName(scope.row.marketStatus)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
        >
        </el-table-column>
        <el-table-column
          prop="createDate"
          label="创建时间"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="图片信息" :visible.sync="showHx">
        <el-form ref="form" :model="aparmentInfo" label-width="160px">
          <el-form-item label="名称">
            <el-input v-model="aparmentInfo.apartmentName"></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="aparmentInfo.apartmentType" placeholder="请选择">
              <el-option label="户型" value="apart"></el-option>
              <el-option label="相册" value="photo"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销售状态">
            <el-select v-model="aparmentInfo.marketStatus" placeholder="请选择">
              <el-option v-for="(type,i) in saleType" :key="i" :label="type.name" :value="type.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              :action="upFileUrl"
              name='file'
              :headers="uploadHeaders"
              list-type="picture-card"
              :file-list="aparmentImg"
              :show-file-list="true"
              :before-upload="beforeImgUpload"
              :on-success="handleAparmentSuccess"
              :on-remove="handleAparmentRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogApartVisible">
              <img width="100%" :src="dialogApartImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="面积">
            <el-input v-model="aparmentInfo.buildingArea"></el-input>
          </el-form-item>
          <el-form-item label="套内面积">
            <el-input v-model="aparmentInfo.insideArea"></el-input>
          </el-form-item>
          <el-form-item label="户型总价">
            <el-input v-model="aparmentInfo.apartmentPrice"></el-input>
          </el-form-item>
          <el-form-item label="户型简介">
            <rich-editor v-model="aparmentInfo.apartmentDescription" style="height: 200px"></rich-editor>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="aparmentInfo.remark"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAparment">保存</el-button>
            <el-button @click="showHx = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-tab-pane>
  </el-tabs>
</template>

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

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

export default {
  name: "BuildingEdit",
  components: {
    EditableTag: () => import("@/components/EditableTag.vue")
  },
  data() {
    var _self = this;
    return {
      upFileUrl: apis.file.upload.url,
      commPrefix: "",
      imgurl: "",
      loadingZm: false,
      activeName: "detail",
      dialogImageUrl: "",
      dialogVisible: false,
      dialogApartImageUrl: "",
      dialogApartVisible: false,
      showHx: false,
      markers: [],
      imgList: [],
      tags: [],
      buildingProperty: [],
      cityName: "123",
      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,
      cityNameList: x => x.cityNameList
    }),
    ...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",
      "getCityName",
      "addBuilding",
      "editBuilding"
    ]),
    ...mapApartmentActions([
      "getApartments",
      "getApartmentDetail",
      "addApartment",
      "editApartment",
      "deleteApartment"
    ]),
    getSaleTypeName(id) {
      return (this.saleType.filter(x => x.id == id)[0] || {}).name;
    },
    onCancel() {
      this.$router.push({ name: "buildinglist" });
      this.$message({
        message: "保存成功！",
        type: "success"
      });
    },
    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;
    },
    handleAvatarSuccess(res) {
      this.imgList = [
        ...this.imgList,
        {
          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();
    },
    handlePreSalePermitSuccess(res) {
      this.building = { ...this.building, preSalePermit: 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;
          this.$message({
            message: "保存成功！",
            type: "success"
          });
        });
      } else {
        this.editApartment(
          JSON.stringify({
            ...this.aparmentInfo,
            img: imgs
          })
        ).then(() => {
          this.getAparmentList();
          this.showHx = false;
          this.$message({
            message: "保存成功！",
            type: "success"
          });
        });
      }
    },
    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();
        });
      });
    },
    initData() {
      this.getCityName();

      if ((this.$route.query.id || "") !== "") {
        this.getAparmentList();
        this.getDetail({ id: this.$route.query.id }).then(data => {
          this.buildingProperty = data.propertyType.split(",");
          this.imgList = data.buildingImg.map(x => {
            return {
              name: x.imgId,
              url: x.url
            };
          });
          this.tags = data.buildingTag.map(x => x.tagName);
        });
      }
    }
  },
  mounted() {
    this.initData();
  }
};
</script>

<style lang="scss" scoped>
.building-form {
  width: 60%;
  min-width: 500px;
}
</style>


<style lang="scss">
.header {
  width: 50px;
  height: 50px;
  img {
    width: 100%;
    height: 100%;
  }
}
.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;
}

.flex-item .amap-demo {
  height: 300px;
}

.el-form-item__content {
  overflow-y: hidden;
  
}
.el-select {
  width: 100% !important;
}

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

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