<template>
  <el-dialog
    :title="dialogTitle"
    v-model="showDialog"
    @open="open()"
    @close="closeDialog(0)"
  >
    <el-form
      ref="formInfo"
      :model="form"
      class="demo-form-inline aaa"
      label-width="150px"
      :rules="rules"
    >
      <el-form-item
        label="模板名称:"
        prop="platformName"
        v-if="dialogTitle == '添加模板'"
      >
        <el-input v-model="form.platformName"></el-input>
      </el-form-item>
      <el-form-item label="" prop="aa">
        <el-tree
          v-if="data.length"
          :data="data"
          :props="defaultProps"
          @node-click="handleNodeClick"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedArr"
          :check-strictly="isStrictly"
          @check="currentChecked"
        />
      </el-form-item>

      <br />

      <div style="text-align: right">
        <el-button @click="closeDialog(0)">取消</el-button>
        <el-button type="primary" @click="submitForm()">保存</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
<script>
// 地图
import AMap from 'AMap'
import { useStore } from 'vuex'
import { defineComponent, ref, watchEffect, onMounted } from 'vue'
import * as api from '@/api/platManage/index.js'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'DialogComponent',
  emits: ['closeDialog'],
  props: {
    show_Dialog: Boolean,
    dialogTitle: String,
    itemInfo: {
      type: Object,
      default: function () {
        return {}
      },
    },
  },
  setup(props, { emit }) {
    const store = useStore()
    const beginTime = ref('')
    const showDialog = ref(false)
    const form = ref({})
    const formInfo = ref(null)
    const nowDate = ref(new Date().getTime())

    const data = ref([])
    const checkedArr = ref([])
    const getPlatformBoxList = ref([])

    const roleValid = (rule, value, callback) => {
      rule
      if (value.length === 0) {
        callback(new Error('角色不能为空'))
      } else {
        callback()
      }
    }

    const disabledDate = (time) => {
      return time.getTime() < Date.now()
    }

    const currentChecked = (nodeObj, SelectedObj) => {
      nodeObj, SelectedObj
      console.log('SelectedObj.checkedNodes')
      console.log(SelectedObj.checkedNodes)
      checkedArr.value = []

      SelectedObj.checkedNodes.forEach((item) => {
        checkedArr.value.push(item.id)
      })
      console.log(checkedArr.value)
    }

    //树结构回显
    function getPlatformMenu() {
      var platformId = ''
      if (props.dialogTitle == '添加模板') {
        platformId = 0
      } else {
        platformId = form.value.id
      }

      api
        .getPlatformMenu({
          platformId: platformId,
        })
        .then((requset) => {
          if (requset.status === 'SUCCESS') {
            console.log('requset.data111')
            console.log(requset.data)
            var jsona = JSON.stringify(requset.data.menus)
            var jsonb = jsona.replace(/"menu"/g, '"label"')
            jsonb = jsonb.replace(/"authority"/g, '"children"')
            jsonb = jsonb.replace(/"name"/g, '"label"')
            var jsonc = JSON.parse(jsonb)
            data.value = jsonc
            console.log('data.value')
            console.log(data.value)

            checkedArr.value = requset.data.checkedKeys
            console.log('checkedArr.value')
            console.log(checkedArr.value)
          } else {
            ElMessage.error(requset.msg)
          }
        })
    }

    // 保存操作
    const submitForm = () => {
      formInfo.value.validate((valid) => {
        if (valid) {
          var params = {}
          if (props.dialogTitle == '添加模板') {
            params = {
              platformId: 0,
              platformName: form.value.platformName,
              menuIds: checkedArr.value,
            }
          } else {
            params = {
              platformId: form.value.id,
              menuIds: checkedArr.value,
            }
          }
          if (checkedArr.value.length) {
            api.updatePlatformMenu(params).then((requset) => {
              if (requset.status === 'SUCCESS') {
                ElMessage.success({
                  message: '新增成功',
                  type: 'success',
                })
                showDialog.value = false
                // closeDialog()
              } else {
                ElMessage.error(requset.msg)
              }
            })
          } else {
            ElMessage.warning('请至少选择一个权限保存')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const marker = ref([])

    function initMap() {
      // AMap start
      var map = new AMap.Map('mapF', {
        resizeEnable: true,
      })
      //为地图注册click事件获取鼠标点击出的经纬度坐标

      var marker = new AMap.Marker({})
      map.on('click', function (e) {
        form.value.geoPosition = e.lnglat.getLng() + ',' + e.lnglat.getLat()

        map.remove([marker])
        marker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        })

        map.add([marker])
      })
      // AMap end
    }

    const open = () => {
      form.value = props.itemInfo
      console.log('form.value')
      console.log(form.value)

      // optionselect()
      getPlatformMenu()
    }

    // 关闭弹框
    const closeDialog = (flag) => {
      checkedArr.value = []
      resetForm()
      showDialog.value = false
      emit('closeDialog', flag)
    }

    function resetForm() {
      formInfo.value.resetFields()
    }

    watchEffect((fn, options) => {
      fn, options
      showDialog.value = props.show_Dialog
    })

    //禁止选择以前的时间
    const pickerEndDate = (time) => {
      const timeRange = 1 * 24 * 60 * 60 * 1000
      return time.getTime() <= Date.now() - timeRange * 1
    }

    onMounted(() => {})

    return {
      pickerEndDate,
      roleValid,
      submitForm,
      closeDialog,
      open,

      data,

      getPlatformMenu,

      // map123,
      store,
      beginTime,
      showDialog,
      checkedArr,
      initMap,
      nowDate,
      disabledDate,
      marker,

      checked: true,
      form,
      formInfo,
      getPlatformBoxList,
      currentChecked,

      rules: {
        platformName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
})
</script>
 
<style scoped lang="scss">
.el-input,
.el-select,
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 240px;
}

.el-form-item {
  margin: 0 0 20px !important;
}
// label样式
.el-form-item__label {
  width: 120px !important;
}
.el-form-item__content {
  margin-left: 100px;
}
.demo-form-inline .el-form-item:not(.user-layout .el-form-item) {
  margin: 0 auto 20px 55px;
}
</style>
<style lang="scss">
// .aaa{

//   .el-form-item:not(.user-layout .el-form-item){
//   width:90%;
//   max-width:100%
// }

// .el-tree>.el-tree-node>.el-tree-node__children .el-tree-node {
//   display:inline-block

// }
// .el-tree>.el-tree-node{
//   display:block

// }

// }
</style>