<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :rules="rules" label-width="120px">
      <h3>基础信息</h3>
      <el-form-item label="医院名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入医院名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="医院等级" prop="level">
        <el-select v-model="form.level" placeholder="请选择医院等级" clearable style="width: 100%">
          <el-option v-for="dict in dict.type.hospital_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医院标签" prop="label">
        <el-input v-model="form.label" placeholder="请输入医院标签" maxlength="150" clearable @keyup.enter.native="handleQuery" />
        <div class="hint">*例如：中医院，综合医院等</div>
      </el-form-item>
      <el-form-item label="所在城市" prop="provinces">
        <!-- <el-input v-model="form.name" placeholder="请输入商户名称" clearable  @keyup.enter.native="handleQuery" /> -->
        <el-cascader ref="refSubCat" v-model="form.provinces" placeholder="请选择所在城市" :options="areaTrea" :props="{ expandTrigger: 'hover' }" @change="handleChange" style="width: 100%"></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址" maxlength="100" clearable @keyup.enter.native="getgetAddressFun" />
      </el-form-item>
      <el-form-item label="经纬度" prop="coordinates">
        <el-input v-model="form.coordinates" disabled placeholder="请输入经纬度" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <div id="container1" class="map-box"></div> -->
      <GDMap ref="gdMapRef" :defaultMarker="defaultMarker" @change="mapchange" />
      <el-form-item label="负责人" prop="responsiblePerson">
        <el-input v-model="form.responsiblePerson" placeholder="请输入负责人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactMobile">
        <el-input v-model="form.contactMobile" placeholder="请输入联系电话" maxlength="11" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客服电话" prop="serviceMobile">
        <el-input v-model="form.serviceMobile" placeholder="请输入客服电话" maxlength="11" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="医院介绍" prop="introduction">
        <editor v-model="form.introduction" :min-height="192" />
      </el-form-item>
      <h3>医院图片</h3>
      <el-form-item label="医院logo" prop="logoUrl">
        <imageUpload v-model="form.logoUrl" :limit="1" unique="logoUrl" />
      </el-form-item>
      <h3>运营配置</h3>
      <el-form-item label="营业时间" prop="businessHours">
        <el-input v-model="form.businessHours" placeholder="请输入营业时间" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="医院序号" prop="sortOrder">
        <el-input-number v-model="form.sortOrder" :min="1" label="排序" :precision="0"></el-input-number>
        <div class="hint">*数字越大在越前面，排序优先需要，其次是创建时间</div>
      </el-form-item>
      <el-form-item label="营业状态" prop="businessStatus">
        <el-select v-model="form.businessStatus" placeholder="请输入状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.hospital_business_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import GDMap from '@/components/gdMap/index'
import { cnAreaTree, hospitalAdd, getLocation, hospitalInfo, hospitalEdit } from '@/api/hospital'
import qqmapPlus from 'qqmap-plus';
import draggable from 'vuedraggable';
export default {
  dicts: ['hospital_level', 'hospital_business_status'],
  components: {
    draggable,
    GDMap
  },
  data () {
    return {
      form: {
        name: undefined,
        level: undefined,
        label: undefined,
        provinces: undefined,
        address: undefined,
        coordinates: undefined,
        responsiblePerson: undefined,
        contactMobile: undefined,
        serviceMobile: undefined,
        introduction: undefined,
        logoUrl: undefined,
        businessHours: undefined,
        sortOrder: undefined,
        businessStatus: undefined,
      },
      rules: {
        name: [
          { required: true, message: '请输入医院名称', trigger: 'change' }
        ],
        level: [
          { required: true, message: '请选择医院等级', trigger: 'change' }
        ],
        label: [
          { required: true, message: '请输入医院标签', trigger: 'change' }
        ],
        provinces: [
          { required: true, message: '请选择所在城市', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'change' }
        ],
        coordinates: [
          { required: true, message: '请选择经纬度', trigger: 'change' }
        ],
        responsiblePerson: [
          { required: true, message: '请输入负责人', trigger: 'change' }
        ],
        contactMobile: [
          { required: true, message: '请输入联系电话', trigger: 'change' }
        ],
        serviceMobile: [
          { required: true, message: '请输入客服电话', trigger: 'change' }
        ],
        // introduction: [
        //   { required: true, message: '请输入医院介绍', trigger: 'change' }
        // ],
        logoUrl: [
          { required: true, message: '请上传医院logo', trigger: 'change' }
        ],
        // businessHours: [
        //   { required: true, message: '请输入营业时间', trigger: 'change' }
        // ],
        sortOrder: [
          { required: true, message: '请输入医院序号', trigger: 'change' }
        ],
        businessStatus: [
          { required: true, message: '请选择营业状态', trigger: 'change' }
        ],
      },
      areaTrea: [],
      shopTypeList: [],
      map: null,
      markers: [],
      lnglat: [],
      geocoder: null,
      buttonLoading: false,
      // 地图回显
      defaultMarker: {
        location: {}
      }
    }
  },
  mounted () {
    this.getCnAreaTree();
    if (this.$route.query.id) {
      this.getDetails(this.$route.query.id)
    } else {
      this.$refs.gdMapRef.initAMap();
    }
    document.documentElement.scrollTop = 0
  },
  methods: {
    getCnAreaTree () {
      cnAreaTree().then(res => {
        this.areaTrea = res.data?.children
      })
    },
    addBusinessProductCategory () {
      this.form.businessProductCategoryList.push({})
    },
    deleteBusinessProductCategory (index) {
      this.form.businessProductCategoryList.splice(index, 1)
    },
    // 省市区选择
    handleChange (value) {
      this.form.provinces = value;
      this.form.provinceId = value[0];
      this.form.provinceName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0];
      this.form.cityId = value[1];
      this.form.cityName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1];
      this.form.areaId = value[2];
      this.form.areaName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2];
    },
    getDetails (id) {
      hospitalInfo(id).then(res => {
        res.data.provinces = [res.data.provinceId, res.data.cityId, res.data.areaId];
        let arr = res.data.coordinates.split(',');
        this.defaultMarker = {
          location: {
            lng: arr[0],
            lat: arr[1]
          },
          address: res.data.address,
        }
        this.form = res.data;
        this.$refs.gdMapRef.initAMap()
      })
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formCopy = JSON.parse(JSON.stringify(this.form))
          this.buttonLoading = true;
          if (this.form.id != null) {
            hospitalEdit(formCopy).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            hospitalAdd(formCopy).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 取消按钮
    cancel () {
      this.$router.go(-1)
    },
    mapchange (e) {
      console.log(e);
      this.form.address = e.address;
      this.form.coordinates = e.location.lng + ',' + e.location.lat;
      this.form.latitude = e.location.lat;
      this.form.longitude = e.location.lng;

    },
    //地图
    initMap (obj = {}) {
      var that = this;
      let key = "KNZBZ-YSB3S-QGNOH-6UN4N-LVGUZ-OJFPQ"
      qqmapPlus.init(key, () => {
        if (obj.lat) {
          that.form.longitude = obj.long;
          that.form.latitude = obj.lat;
        } else {
          obj.long = that.form.longitude = 114.30656433105469;
          obj.lat = that.form.latitude = 30.588281906904278;
        }
        var myLatlng = new qq.maps.LatLng(obj.lat, obj.long);
        var myOptions = {
          zoom: 16,
          center: myLatlng,
          mapTypeId: qq.maps.MapTypeId.ROADMAP
        };
        that.map = new qq.maps.Map(document.getElementById('container1'), myOptions);
        var marker = new qq.maps.Marker({
          position: myLatlng,
          map: that.map
        });
        // 获取点击后的地址
        qq.maps.event.addListener(that.map, 'click', function (event) {
          if (marker) {
            marker.setMap(null);
            marker = null;
          }
          // that.$refs.formRef.clearValidate();
          // 获取点击后的地图坐标
          that.form.longitude = event.latLng.getLng();
          that.form.latitude = event.latLng.getLat();
          that.$set(that.form, 'coordinates', event.latLng.getLng() + ',' + event.latLng.getLat());
          marker = new qq.maps.Marker({
            position: new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng()),
            map: that.map
          });
          getLocation(event.latLng.getLat() + ',' + event.latLng.getLng()).then(res => {
            that.form.address = res.data.address + res.data.formatted_addresses.rough
          })
        });
      });
    },
  }
}
</script>

<style lang='scss' scoped>
.el-form {
  width: 800px;
}
.hint {
  font-size: 12px;
  color: red;
}
.map-box {
  width: calc(100% - 120px);
  height: 300px;
  margin-bottom: 30px;
  box-sizing: border-box;
  margin-left: 120px;
}
.flex {
  display: flex;
  margin-bottom: 10px;
  .el-button {
    margin-left: 10px;
  }
}
h3 {
  width: 120px;
  font-weight: 700;
  text-align: right;
}
.flex-bet {
  display: flex;
  justify-content: space-between;
}
</style>