<template>
  <div>

    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="true"
               :model="formData"
               :rules="dataRule"
               :disabled="formType === 'detail'"
               class="form">

        <el-form-item label="所属网格"
                      label-width="150px"
                      style="display: block"
                      prop="gridId">
          <el-select v-model="formData.gridId"
                     filterable
                     placeholder="请选择"
                     @change="handleGridChange"
                     clearable>
            <el-option v-for="item in optionsG"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="服务类型"
                      label-width="150px"
                      style="display: block"
                      prop="serviceType">
          <el-select v-model="formData.serviceType"
                     filterable
                     :disabled="disabled"
                     placeholder="请选择"
                     clearable>
            <el-option v-for="item in serviceTypeList"
                       :key="item.serviceType"
                       :label="item.serviceTypeName"
                       :value="item.serviceType">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="申请人"
                      label-width="150px"
                      style="display: block"
                      prop="applicantId">
          <el-select v-model="formData.applicantId"
                     filterable
                     placeholder="请选择"
                     @change="handleUserChange"
                     clearable>
            <el-option v-for="item in demandUserList"
                       :key="item.demandUserId"
                       :label="item.label"
                       :value="item.demandUserId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="住址"
                      style="display: block"
                      label-width="150px"
                      prop="applicantAddress">
          <el-input v-model="formData.applicantAddress"
                    class="item_width_1"
                    placeholder="请输入住址"></el-input>
        </el-form-item>
        <el-form-item label="服务内容"
                      style="display: block"
                      label-width="150px"
                      prop="serviceContent">
          <el-input v-model="formData.serviceContent"
                    class="item_width_1"
                    type="textarea"
                    placeholder="请输入服务内容"></el-input>
        </el-form-item>

        <el-form-item label="联系电话"
                      style="display: block"
                      label-width="150px"
                      prop="applicantMobile">
          <el-input v-model="formData.applicantMobile"
                    class="item_width_1"
                    placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="负责人"
                      style="display: block"
                      label-width="150px"
                      prop="principalName">
          <el-input v-model="formData.principalName"
                    class="item_width_1"
                    placeholder="请输入负责人"></el-input>
        </el-form-item>

        <el-form-item label="服务时间"
                      style="display: block"
                      label-width="150px"
                      prop="serviceTime">
          <el-input v-model="formData.serviceTime"
                    class="item_width_1"
                    placeholder="请输入服务时间"></el-input>
        </el-form-item>

        <el-form-item label="备注"
                      style="display: block"
                      label-width="150px"
                      prop="remark">
          <el-input v-model="formData.remark"
                    class="item_width_1"
                    type="textarea"
                    placeholder="请输入备注"></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 { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import {requestGet} from "../../../../js/dai/request";



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

let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      agencyId: '',
      btnDisable: false,
      disabled: false,
      applicantId: '',
      keyWords: '',
      formData: {
        serviceType: '',
        serviceTypeName: '',
        gridId: '',
        gridName: '',
        applicantAddress: '',
        applicantName: '',
        applicantId: '',
        serviceContent: '',
        applicantMobile: '',
        principalName: '',
        serviceTime: '',
        remark: ''
      },
      optionsG: [],
      serviceTypeList: [],
      publicServiceData: {},
      demandUserList: [],
    }
  },
  components: {},
  async created () {
    this.getGridList('query')
    this.getServiceTypeList()
    // this.getDemandUserList()
  },
  mounted () {
  },

  methods: {

    async initForm (type, row) {
      this.startLoading()
      this.$refs.ref_form.resetFields();

      //获取服务事项
      await this.getServiceTypeList()
      this.serviceTypeList.forEach(s => {
        if (s.serviceType === this.formData.serviceType){
          this.disabled = s.enabled
        }
      })
      this.getGridList(type)
      this.formType = type
      if (type === 'edit'){
        this.formData = row
        this.getDemandUserList(this.formData.gridId)
      }
      this.endLoading()
    },

    //获取服务事项下拉框
    async getServiceTypeList () {
      const url = "/heart/workdiaryService/serviceType/avaliableList"
      // let url = 'http://yapi.elinkservice.cn/mock/245/heart/workdiaryService/serviceType/page'
      let params = {
        pageNo: 1,
        pageSize: 10000
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.serviceTypeList = data.list
      } else {
        this.$message.error(msg)
      }
    },
    async getDemandUserList (gridId) {
      const { user } = await this.$store.state;
      const params = {
        agencyId: user.agencyId,
        gridId: gridId,
        name: "",
      };
      // addorupdate
      await this.$http
              .post("/epmetuser/icresiuser/demandusers", params)
              .then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg);
                } else {
                  this.demandUserList = res.data;
                  console.log(this.demandUserList)
                }
              })
              .catch(() => {
                return this.$message.error("网络错误");
              });
    },
    //加载组织
    async getGridList (type) {
      const { user } = await this.$store.state;
      const url = '/gov/org/customergrid/gridoption'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/icPublicService/detail'
      let params = {
        agencyId: user.agencyId,
        purpose: type,
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.optionsG = data;
      } else {
        this.$message.error(msg)
      }
    },
    handleGridChange (val) {
      this.getDemandUserList(this.formData.gridId);
    },
    async handleUserChange () {
      let homeId
      this.demandUserList.forEach(d => {
        if (d.demandUserId === this.formData.applicantId){
           homeId = d.houseId
        }
      })
      let url = '/gov/org/ichouse/'+homeId
      let params = {}
      const { data, code, msg } = await requestGet(url)
      if (code === 0) {
        this.formData.applicantAddress = data.fullName
      } 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.addUnit()
        }
      })
    },
    async addUnit () {
      let url = ''
      if (this.formType === 'add') {
        url = '/heart/workdiaryService/record/save'
        // url = 'http://yapi.elinkservice.cn/mock/245/heart/workdiaryService/record/save'
      } else {
        url = '/heart/workdiaryService/record/update'
        // url = 'http://yapi.elinkservice.cn/mock/245/heart/workdiaryService/record/update'
      }
      const { data, code, msg, internalMsg } = await requestPost(url, this.formData)
      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()
        this.$emit('dialogOk')
        this.btnDisable = false
      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }

    },

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

    },
    resetData () {
      this.demandUserList = []
      this.optionsG = []
      this.formData = {
        serviceType: 0,
        gridId: '',
        applicantAddress: '',
        applicantName: '',
        applicantId: '',
        serviceContent: '',
        applicantMobile: '',
        principalName: '',
        serviceTime: '',
        remark: ''
      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {
        gridId: [
          { required: true, message: '所属网格不能为空', trigger: 'blur' },
        ],
        serviceType: [
          { required: true, message: '服务类型不能为空', trigger: 'blur' }
        ],
        applicantAddress: [
          { required: true, message: '住址不能为空', trigger: 'blur' }
        ],
        applicantId: [
          { required: true, message: '申请人不能为空', trigger: 'blur' }
        ],
        serviceContent: [
          { required: true, message: '服务内容不能为空', trigger: 'blur' }
        ],
        serviceTime: [
          { required: true, message: '服务时间不能为空', trigger: 'blur' }
        ],
        applicantMobile: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' }
        ]
      }
    },

  },
  props: {

    typeList: {
      type: Array,
      default: []
    },

  }
}
</script>
<style scoped>
.div_map {
  position: relative;
}
.div_searchmap {
  z-index: 5000;
  position: absolute;
  top: 5px;
  left: 5px;
}
</style>

<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
