<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <div v-if="initLoading"
           class="m-row">
        <div class="m-info">
          <div class="info-prop">
            <span class="info-title-2">服务名称：</span>
            <span>{{ formData.serviceName||'--'  }}</span>
          </div>

          <div class="info-prop">
            <span class="info-title-2">服务组织：</span>
            <span>{{ serviceOrgName||'--'  }}</span>
          </div>

          <div class="info-prop">
            <span class="info-title-2">服务范围：</span>
            <span>{{ formData.gridIdListName ||'--' }}</span>
          </div>

          <div class="info-prop">
            <span class="info-title-2">政策依据：</span>
            <span>{{ formData.policyName||'--'  }}</span>
            <el-button v-if="formData.policyId"
                       style="margin-left: 10px"
                       type="primary"
                       size="small"
                       @click="handlePersonList">预览</el-button>
          </div>
          <div class="info-prop">
            <span class="info-title-2">经办人：</span>
            <span>{{ formData.principalName||'--'  }}</span>
          </div>
          <div class="info-prop">
            <span class="info-title-2">联系方式：</span>
            <span>{{ formData.principalContact||'--' }}</span>
          </div>
          <div class="info-prop">
            <span class="info-title-2">服务时间：</span>
            <span>{{ formData.serviceTimeStart||'--' }}</span>至
            <span>{{ formData.serviceTimeEnd||'--' }}</span>
          </div>
          <div class="info-prop">
            <span class="info-title-2">备注：</span>
            <span>{{ formData.remark||'--' }}</span>
          </div>

          <div v-show="formData.serviceStatus==='completed'">
            <h3 class="d-h3">反馈内容</h3>

            <div class="info-prop">
              <span class="info-title-2">服务目标：</span>
              <span>{{ feedbackFormData.serviceGoal||'--'  }}</span>
            </div>
            <div class="info-prop">
              <span class="info-title-2">服务效果：</span>
              <span>{{ feedbackFormData.serviceEffect||'--'  }}</span>
            </div>
            <div class="info-prop">
              <span class="info-title-2">服务人数：</span>
              <span>{{ feedbackFormData.servicePeopleNumber||0  }}</span>
            </div>

            <div class="info-prop">
              <span class="info-title-2">服务状态：</span>
              <span>{{ feedbackFormData.serviceStatusShow||'--'  }}</span>
            </div>
            <div class="info-prop">
              <span class="info-title-2">满意度：</span>
              <span>{{ feedbackFormData.satisfactionShow||'--'  }}</span>
            </div>

            <div class="info-prop">
              <span class="info-title-2">地理位置：</span>
              <span>{{ feedbackFormData.address||'--'  }}</span>
            </div>

            <div class="info-prop">
              <span class="info-title-2">地图位置：</span>
              <div class="div_map">

                <div id="app_detail"></div>

              </div>
            </div>

            <div class="info-prop">
              <span class="info-title-2">附件：</span>
              <file-list v-if="fileList.length>0"
                         :fileList="fileList"></file-list>
              <span v-else>--</span>

            </div>

          </div>

        </div>
      </div>

    </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> -->

    <el-dialog v-if="showPersonList"
               :visible.sync="showPersonList"
               :append-to-body="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'政策预览'"
               width="1150px"
               top="5vh"
               class="dialog-h"
               @closed="showPersonList = false">
      <person-list ref="ref_detail_form"
                   :policyId="policyId"
                   :ruleList="ruleList"
                   @handleOk="handleOk"
                   @handleClose="handleClose">
      </person-list>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import personList from "../policy/personList";
import fileList from '@/views/components/fileList'


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

let loading // 加载动画
export default {
  data () {

    return {


      initLoading: false,

      keyWords: '',
      formData: {},

      feedbackFormData: {
        serviceProjectId: '',//	服务项目id	
        serviceName: '',
        serviceGoal: '',//	服务目标	
        serviceEffect: '',//	服务效果	
        servicePeopleNumber: null,//	服务人数	
        serviceStatus: 'completed',//	服务状态。in_service服务中；completed:已完成	
        satisfaction: '',//满意度。不满意:bad、基本满意:good、非常满意:perfect	
        longitude: '',//	经度	
        latitude: '',//	维度	
        address: '',
        fileList: [],//	附件列表
      },


      policyId: "",
      showPersonList: false,
      ruleList: [],
      policyList: [],




    }
  },
  components: { personList, fileList },
  async mounted () {
    await this.getPolicyList()
    // if (this.serviceRecordId) {//详情
    await this.loadInfo()
    this.initLoading = true

    if (this.formData.serviceStatus === 'completed') {
      this.$nextTick(() => {
        this.initMap()
      })
    }
  },


  methods: {

    diaDestroy () {
      if (map) {
        map.destroy()
      }
    },

    //加载组织数据
    async handlePersonList () {
      if (!this.formData.policyId) {
        this.$message.info('请先选择政策')
        return false
      }

      this.policyId = this.formData.policyId
      await this.loadRuleList()

      this.showPersonList = true;
    },

    async loadRuleList () {

      const url = "/heart/policy/rulelist/" + this.policyId

      let params = {}

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

      if (code === 0) {
        this.ruleList = data

      } else {
        this.$message.error(msg)
      }

    },

    handleClose () {
      this.showPersonList = false
    },


    async getPolicyList () {
      const url = '/heart/policy/policyListSelect'

      let params = {}

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

      if (code === 0) {
        this.policyList = data
      } else {
        this.$message.error(msg)
      }
    },
    //加载组织
    async loadInfo () {
      const url = '/heart/icServiceRecordV2/detail'

      let params = {
        serviceRecordId: this.serviceRecordId
      }

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

      if (code === 0) {
        this.formData = { ...data }
        this.formData.serviceRecordId = this.serviceRecordId
        this.feedbackFormData = { ...data.feedback }
        this.formData.policyName = ''
        this.formData.gridIdListName = ''
        this.feedbackFormData.serviceStatusShow = ''
        this.feedbackFormData.satisfactionShow = ''

        let arr = []
        this.formData.gridIdList.forEach(element => {
          arr.push(element.objectName)
        });
        this.formData.gridIdListName = arr.join(',')
        this.statusArray.forEach(element => {
          if (this.formData.serviceStatus === element.value) {
            this.feedbackFormData.serviceStatusShow = element.label
          }
        });
        this.satisfyArray.forEach(element => {
          if (this.feedbackFormData.satisfaction === element.value) {
            this.feedbackFormData.satisfactionShow = element.label
          }
        });
        this.policyList.forEach(element => {
          if (this.formData.policyId === element.policyId) {
            this.formData.policyName = element.title
          }
        });

        this.fileList = []
        if (data.feedback && data.feedback.fileList && data.feedback.fileList.length > 0) {
          data.feedback.fileList.forEach(element => {
            let obj = {
              name: element.name,
              format: element.format,
              url: element.url,
              type: element.type

            }
            this.fileList.push(obj)
          });
        }




      } else {
        this.$message.error(msg)
      }
    },



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

    },



    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      // 定义地图中心点坐标
      let { latitude, longitude } = this.$store.state.user;
      console.log('lat' + latitude + ',lon' + longitude)

      if (this.formData.latitude && this.formData.longitude) {
        latitude = this.formData.latitude
        longitude = this.formData.longitude
      }
      if (!latitude || latitude == "" || latitude == "0") {
        latitude = 39.9088810666821;
        longitude = 116.39743841556731;
      }
      var center = new window.TMap.LatLng(latitude, latitude)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new window.TMap.Map(document.getElementById('app_detail'), {
        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
          // 显示搜索到的地址
        });
    },
    handleOk () {
      this.showPersonList = false
    },

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


        serviceTimeStart: [
          { required: true, message: '服务时间不能为空', trigger: 'blur' }
        ],


      }
    },
  },
  props: {

    serviceRecordId: {
      type: String,
      required: true
    },
    serviceOrgName: {
      type: String,
      required: true
    },


    satisfyArray: {
      type: Array,
      default () {
        return []
      }
    },
    statusArray: {
      type: Array,
      default () {
        return []
      }
    },
  }
}
</script>


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