<template>
  <div>
    <div class="dialog-h-content scroll-h">

      <el-form ref="ref_form"
               :inline="true"
               :model="formData"
               :disabled="formType==='detail'"
               :rules="dataRule"
               class="div_form">

        <el-form-item label="服务分类"
                      label-width="150px"
                      prop="serviceCategoryKey">
          <span>{{formData.serviceCategoryName}}</span>

          <!-- <el-select v-model="formData.serviceCategoryKey"
                     placeholder="请选择"
                     clearable
                     class="item_width_1">
            <el-option v-for="(item,index) in categrayArray"
                       @click.native="hancleClickCategray(index)"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select> -->
        </el-form-item>

        <el-form-item label="服务项目"
                      prop="serviceProjectId"
                      label-width="150px"
                      style="display: block">
          <span>{{formData.serviceProjectName}}</span>
          <!-- <el-select class="item_width_1"
                     v-model="formData.serviceProjectId"
                     placeholder="请选择"
                     filterable
                     clearable>
            <el-option v-for="(item,index) in projectList"
                       @click.native="hancleClickProject(index)"
                       :key="item.serviceProjectId"
                       :label="item.serviceName"
                       :value="item.serviceProjectId">
            </el-option>
          </el-select> -->

        </el-form-item>
        <el-form-item label="服务组织"
                      prop="serviceOrgId"
                      label-width="150px"
                      style="display: block">
          <span>{{formData.serviceOrgName}}</span>
          <!-- <el-select class="item_width_1"
                     v-model="formData.serviceOrgId"
                     placeholder="请选择"
                     filterable
                     clearable>
            <el-option v-for="item in orgList"
                       :key="item.icServiceOrgId"
                       :label="item.orgName"
                       :value="item.icServiceOrgId">
            </el-option>
          </el-select> -->

        </el-form-item>

        <el-form-item label="服务范围"
                      prop="serviceScope"
                      label-width="150px"
                      style="display: block">
          <div v-for="item in formData.serviceScope"
               :key="item.objectId">
            <div>{{item.objectName}}</div>
          </div>
          <!-- <el-cascader class="item_width_1"
                       ref="myCascader"
                       v-model="scopeIdArray"
                       :key="iscascaderShow"
                       :options="casOptions"
                       :props="optionProps"
                       :show-all-levels="false"
                       @change="handleChangeScope"></el-cascader> -->
        </el-form-item>

        <el-form-item label="经办人"
                      prop="principalName"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入联系人姓名"
                    v-model="formData.principalName">
          </el-input>
        </el-form-item>
        <el-form-item label="联系方式"
                      prop="principalContact"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入联系人电话"
                    v-model="formData.principalContact">
          </el-input>
        </el-form-item>

        <el-form-item label="服务时间"
                      label-width="150px"
                      prop="serviceTimeStart">
          <el-date-picker v-model="formData.serviceTimeStart"
                          :picker-options="startPickerOptions"
                          class="item_width_2"
                          type="date"
                          value-format="yyyy-MM-dd"
                          value="yyyy-MM-dd"
                          placeholder="开始时间">
          </el-date-picker>
          <span class="data-tag">至</span>
          <el-date-picker v-model="formData.serviceTimeEnd"
                          :picker-options="endPickerOptions"
                          class="item_width_2 data-tag"
                          type="date"
                          value-format="yyyy-MM-dd"
                          value="yyyy-MM-dd"
                          placeholder="结束时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注"
                      prop="remark"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="500"
                    show-word-limit
                    :rows="3"
                    placeholder="请输入备注，不超过500字"
                    v-model="formData.remark"></el-input>
        </el-form-item>

      </el-form>

    </div>

    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 v-if="formType != 'detail'"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'



var map
var search
var markers
var infoWindowList
var geocoder // 新建一个正逆地址解析类

let loading // 加载动画
export default {
  data () {
    let endDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      if (this.formData.serviceTimeStart) {
        let serviceTimeStart = new Date(this.formData.serviceTimeStart)
        return time.getTime() > nowData || time.getTime() < serviceTimeStart || time.getTime() === serviceTimeStart
      } else {
        return time.getTime() > nowData
      }

    }
    let startDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      return time.getTime() > nowData
    }

    return {


      btnDisable: false,

      keyWords: '',
      formData: {
        unitName: '',
        serviceMatterList: [],
        type: '',
        contact: '',
        contactMobile: '',
        memberCount: 0,
        remark: '', //备注【最大500字】
        address: '', //详细地址
        longitude: 36.0722275, //经度
        latitude: 120.38945519 //纬度
      },
      serviceList: [],//服务list

      endPickerOptions: {
        disabledDate: endDisabledDate
      },
      startPickerOptions: {
        disabledDate: startDisabledDate
      },


      projectList: [],

    }
  },
  components: {},
  mounted () {
    if (this.serviceRecordId) {//详情
      this.loadInfo()
    }
    // this.initMap()
    console.log('mounted')
  },


  methods: {


    //加载组织
    async loadInfo () {
      const url = `/heart/icServiceProject/service/detail/${this.serviceRecordId}`
      // const url = 'http://yapi.elinkservice.cn/mock/245/heart/icpartyunit/detail' + this.serviceRecordId
      let params = {}

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.formData = { ...data }
        this.formData.serviceRecordId = this.serviceRecordId
      } else {
        this.$message.error(msg)
      }
    },



    async handleComfirm () {

      this.btnDisable = true
      setTimeout(() => {
        this.btnDisable = false
      }, 10000)
      this.$refs['ref_form'].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj)
          this.btnDisable = false
        } else {
          this.editFuwu()
        }

      })


    },
    async editFuwu () {
      const regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/; //手机号码
      if (regPhone.test(this.formData.principalContact) === false) {
        this.btnDisable = false
        this.$message({
          type: 'warning',
          message: '请输入正确的手机号码'
        })
        return false;
      }

      let url = '/heart/icServiceProject/service/update'
      // let url = "http://yapi.elinkservice.cn/mock/245/heart/icServiceProject/service/update"


      const { data, code, msg } = await requestPost(url, this.formData)

      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()

        this.$emit('handleOk')
      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }

    },

    handleCancle () {
      this.resetData()
      this.$emit('handleClose')

    },

    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      // 定义地图中心点坐标
      var center = new window.TMap.LatLng(36.0722275, 120.38945519)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new window.TMap.Map(document.getElementById('app'), {
        center: center, // 设置地图中心点坐标
        zoom: 17.2, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45 // 设置地图旋转角度
      })

      search = new window.TMap.service.Search({ pageSize: 10 })
      // 新建一个地点搜索类
      markers = new TMap.MultiMarker({
        map: map,
        geometries: []
      })
      infoWindowList = Array(10)

      geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类

      // 监听地图平移结束
      map.on('panend', () => {
        this.handleMoveCenter()
      })
      this.handleMoveCenter()
      this.convert()
    },

    setMarker (lat, lng) {
      markers.setGeometries([])
      markers.add([
        {
          id: '4',
          styleId: 'marker',
          position: new TMap.LatLng(lat, lng),
          properties: {
            title: 'marker4'
          }
        }
      ])
    },

    handleSearchMap () {
      infoWindowList.forEach((infoWindow) => {
        infoWindow.close()
      })
      infoWindowList.length = 0
      markers.setGeometries([])
      // 在地图显示范围内以给定的关键字搜索地点
      search
        .searchRectangle({
          keyword: this.keyWords,
          bounds: map.getBounds()
        })
        .then((result) => {
          let { data } = result
          if (Array.isArray(data) && data.length > 0) {
            const {
              location: { lat, lng }
            } = data[0]


            map.setCenter(new TMap.LatLng(lat, lng))
            this.setMarker(lat, lng)
            this.formData.latitude = lat
            this.formData.longitude = lng
            this.convert()
          } else {
            this.$message.error('未检索到相关位置坐标')
          }
        })
    },

    handleMoveCenter () {
      //修改地图中心点
      const center = map.getCenter()
      const lat = center.getLat()
      const lng = center.getLng()
      this.formData.latitude = lat
      this.formData.longitude = lng
      this.setMarker(lat, lng)
      this.convert(lat, lng)
    },

    convert (lat, lng) {
      markers.setGeometries([]);
      // var input = document.getElementById('location').value.split(',');
      let location
      if (lat && lng) {
        location = new TMap.LatLng(lat, lng);
      } else {
        location = new TMap.LatLng(this.formData.latitude, this.formData.longitude);
      }

      // map.setCenter(location);
      markers.updateGeometries([
        {
          id: 'main', // 点标注数据数组
          position: location,
        },
      ]);
      geocoder
        .getAddress({ location: location }) // 将给定的坐标位置转换为地址
        .then((result) => {
          this.formData.address = result.result.address
          // 显示搜索到的地址
        });
    },


    resetData () {
      this.formData = {
        serviceCategoryKey: '',//服务分类id	
        serviceProjectId: '',//服务项目id	
        serviceOrgId: '',//服务组织id	
        serviceScope: [],//
        principalName: '',//经办人(责任人)姓名	
        principalContact: '',//经办人联系方式	
        serviceTimeStart: '',//服务起始时间yyyy-MM-dd	
        serviceTimeEnd: '',//服务截止时间yyyy-MM-dd	
        remark: '',//

      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {

        serviceCategoryKey: [
          { required: true, message: '服务类别不能为空', trigger: 'blur' },
        ],
        serviceProjectId: [
          { required: true, message: '服务项目不能为空', trigger: 'blur' }
        ],

        serviceOrgId: [
          { required: true, message: '服务组织不能为空', trigger: 'blur' }
        ],
        serviceTimeStart: [
          { required: true, message: '服务时间不能为空', trigger: 'blur' }
        ],
        serviceScope: [
          { required: true, message: '服务范围不能为空', trigger: 'blur' }
        ],

      }
    },
  },
  props: {

    serviceRecordId: {
      type: String,
      required: true
    },
    formType: {//表单操作类型 add新增，edit编辑，detail详情,feedback反馈
      type: String,
      required: true
    },
    categrayArray: {
      type: Array,
      required: true,
      default () {
        return []
      }
    }
  }
}
</script>


<style lang="scss" scoped >
@import "@/assets/scss/modules/management/form-main.scss";
</style>
