<template>
  <div>
    <!-- 侧边栏 -->
    <b-list-group id="list" v-show="isShow">
      <!-- header -->
      <b-list-group-item id="header">
          <i class="fa fa-list" aria-hidden="true"></i>&nbsp; 列表
        <button type="button" class="close" aria-label="Close"  @click="changeShow">
          <i class="fa fa-times" aria-hidden="true"></i>
        </button>
      </b-list-group-item>
      <!-- body -->
      <b-list-group-item id="body" style="overflow:auto">
          <b-tabs content-class="mt-3" v-model="tabIndex">
            <!-- 通知 -->
            <b-tab>
              <template v-slot:title>
                <i class="fa fa-mobile" aria-hidden="true"></i>
                通知
              </template>
              <div>
                  <b-list-group  class="listGroup" v-for="(item,index) in data.notice" :key=index>
                      <b-list-group-item href="#" @click.self="selectItem($event,index)">
                        ● {{item.title|ellipsis}}
                        <span class="float-right font-italic font-weight-light" style="font-size:12px">{{item.time}}</span>
                      </b-list-group-item>
                  </b-list-group>
                </div>
            </b-tab>
            <!-- 报道 -->
            <b-tab>
              <template v-slot:title>
                <i class="fa fa-commenting-o" aria-hidden="true"></i>
                报道
              </template>
              <div>
                <b-list-group  class="listGroup" v-for="(item,index) in data.report" :key=index>
                  <b-list-group-item href="#"
                  @click.self="selectItem($event,index)">
                    ● {{item.title|ellipsis}}
                    <span class="float-right font-italic font-weight-light" style="font-size:12px">{{item.time}}</span>
                  </b-list-group-item>
                </b-list-group>
             </div>
            </b-tab>
            <!-- 文化 -->
            <b-tab>
              <template v-slot:title>
                <i class="fa fa-paper-plane-o" aria-hidden="true"></i>
                文化
              </template>
              <div>
                <b-list-group class="listGroup" v-for="(item,index) in data.culture" :key=index>
                  <b-list-group-item href="#" @click.self="selectItem($event,index)">
                    ● {{item.title|ellipsis}}
                  </b-list-group-item>
                </b-list-group>
             </div>
            </b-tab>
          </b-tabs>
      </b-list-group-item>
      <!-- footer -->
      <b-list-group-item id="footer" align='center'>
        <b-button-group  style="background:rgb(255,255,255)" v-show="tabIndex !== 2 && $store.state.isLogin === true" >
          <b-button variant="outline-dark" title="添加记录"  @click="$bvModal.show('addModal')"><i class="fa fa-plus" aria-hidden="true"  ></i></b-button>

          <b-button variant="outline-dark" title="删除记录" v-show="toolShow.delete" @click="deleteItem()"><i class="fa fa-minus" aria-hidden="true"></i></b-button>
           <b-button disabled  title="删除记录" v-show="!toolShow.delete" ><i class="fa fa-minus" aria-hidden="true"></i></b-button>

          <b-button variant="outline-dark" title="刷新记录" @click="refresh"><i class="fa fa-refresh" aria-hidden="true" title='刷新'></i></b-button>

         <b-button variant="outline-success" v-show="toolShow.submit" title="应用更改" @click="submitChange"><i class="fa fa-check" aria-hidden="true"></i> </b-button>
          <b-button  disabled title="应用更改" v-show="!toolShow.submit"><i class="fa fa-check" aria-hidden="true"></i> </b-button>

          <b-button variant="outline-warning" title="放弃更改" @click="giveupChange"><i class="fa fa-times" aria-hidden="true"></i></b-button>
        </b-button-group>
        <div class="font-italic pt-1" style="font-size:12px">@Powered by CDUT</div>
      </b-list-group-item>
    </b-list-group>

    <!-- 外部控制按钮 -->
    <div id="btn">
      <!-- 列表 按钮 -->
      <b-button  @click="changeShow" class="mr-2" title="列表">
        <i class="fa fa-list" aria-hidden="true"></i>
      </b-button>

      <!-- 登陆 按钮 -->
      <b-button variant="primary" v-if="!$store.state.isLogin" @click="$bvModal.show('loginModal')">
        <i class="fa fa-id-card" aria-hidden="true"></i> 登陆
      </b-button>

      <!-- 登陆状态 按钮 -->
      <span v-else>
        <!-- 按钮 -->
        <b-button id="logout"  variant="primary" class="m-2" >
        <i class="fa fa-user-circle-o fa-lg" varient='info' aria-hidden="true"></i>
        </b-button>
        <!-- popover -->
        <b-popover target="logout"  triggers="hover" placement="bottomleft">
          <template v-slot:title>
            <em>Hello,</em><code> {{$store.state.user.name}} </code>!
          </template>
          <b-list-group flush>
            <b-list-group-item href="#" disabled>修改密码</b-list-group-item>
            <b-list-group-item href="#">退出登陆</b-list-group-item>
          </b-list-group>
        </b-popover>
      </span>
    </div>

    <!-- addModal -->
    <b-modal id="addModal" title="发布工具" scrollable>
      <template v-slot:modal-title>
        <i class="fa fa-plus" aria-hidden="true"  ></i>
      </template>
      <b-form  @submit.prevent="submit_addModal">
        <b-form-group
          id="input-group-1"
          label="* 标题："
          label-for="input-1"
          description="注：输入的标题应小于六十字长度"
        >
          <b-form-input
            id="input-1"
            v-model="form.title"
            required
            placeholder="Enter title"
          ></b-form-input>
        </b-form-group>

        <b-form-group id="input-group-3" label="* 地点：" label-for="input-3">
          <b-form-select
            id="input-3"
            v-model="form.place"
            :options="places"
            required
          ></b-form-select>
        </b-form-group>

        <b-form-group id="input-group-5" label="* 类型：" label-for="input-5">
          <b-form-select
            id="input-5"
            v-model="form.type"
            :options="types"
            required
          ></b-form-select>
        </b-form-group>

        <b-form-group id="input-group-4" label="* 概要:" label-for="input-4">
          <b-form-textarea
            id="input-4"
            v-model="form.content"
            required
            placeholder="Enter abstract"
          ></b-form-textarea>
        </b-form-group>

        <b-form-group id="input-group-6" label="* 时间：" label-for="input-6">
          <b-form-input
            id="input-6"
            v-model="form.time"
            type = 'date'
            required
          ></b-form-input>
        </b-form-group>

        <b-form-group id="input-group-2" label="详情网址：" label-for="input-2">
          <b-form-input
            id="input-2"
            v-model="form.url"
            type="url"
            placeholder="Enter url"
          ></b-form-input>
        </b-form-group>

        <b-button type="reset" variant="danger">重置</b-button>
        <b-button type="submit" variant="primary">提交</b-button>
      </b-form>
      <template v-slot:modal-footer>
        <b-button type="reset" variant="secondary" @click="$bvModal.hide('addModal')">关闭</b-button>
      </template>
    </b-modal>

    <!-- loginModal -->
    <b-modal id="loginModal" title="登 陆">
      <template v-slot:modal-title>
        <div class="align-center"><i class="fa fa-id-card" aria-hidden="true"></i> Login</div>
      </template>
      <b-form @submit.prevent="submit_loginModal()">
         <b-form-group label="账号：" label-for="input-2"  label-cols-sm="2">
          <b-form-input
            id="input-user"
            v-model="login.account"
            required
            placeholder="Enter account"
          >
          </b-form-input>
        </b-form-group>

        <b-form-group label="密码：" label-for="input-password" label-cols-sm="2" >
          <b-form-input
            id="input-password"
            v-model="login.password"
            type="password"
            required
            placeholder="Enter password"
          ></b-form-input>
          <b-form-invalid-feedback :state="login.isRight">
            <b-icon icon="x-octagon-fill"></b-icon>&nbsp;{{login.errorMessage}}
          </b-form-invalid-feedback>
        </b-form-group>
        <div class="text-center">
          <b-button type="reset" variant="danger" >重置</b-button>
          <b-button type="submit" variant="primary">提交</b-button>
        </div>
      </b-form>
         <template v-slot:modal-footer>
        <b-button type="reset" variant="secondary" @click="$bvModal.hide('loginModal')">关闭</b-button>
      </template>
    </b-modal>

    <!-- Alert -->
    <div id="alert"
     v-show="alert.dismissCountDown > 0"
      >
      <b-alert show variant="success" fade v-show="alert.type === 'success'" size='sm'>{{alert.message}}</b-alert>
      <b-alert show variant="danger" fade v-show="alert.type === 'danger'" size='sm'>{{alert.message}}</b-alert>
    </div>
  </div>
</template>
<script>
// eventBus公共实例
import bus from '../../static/js/eventBus'

export default {
  name: 'PC',
  data () {
    return {
      // 侧边栏显示控制
      isShow: false,
      // tabs控制
      tabIndex: 0,
      // 登陆表单
      login: {
        account: '',
        password: '',
        isRight: true,
        errorMessage: '账号或密码输入错误'
      },
      //  列表数据
      data: {
        notice: [],
        report: [],
        culture: []
      },
      // 列表备份数据
      colonData: {
        notice: [],
        report: [],
        culture: []
      },
      // 工具栏可视控制
      toolShow: {
        delete: false,
        submit: false
      },
      // 已选择的DOM
      selected: null,
      // 操作目标的数据下标
      selectedIndex: null,
      // 地点选择输入
      places: [],
      // 类型选择输入
      types: ['报道', '通知'],
      //  预删除的消息id号
      deleteArr: [],
      // 消息发布的表单绑定数据
      form: {
      },
      // 确定修改时消息删除的消息id汇总
      submitDeleteID: [],
      //  Alert content
      alert: {
        message: '',
        type: 'success',
        //  显示的总计秒数
        dismissSecs: 3,
        // 读秒
        dismissCountDown: 0
      }

    }
  },
  methods: {
    /**
     * @description:计时显示alert窗口
     * @returns {void}
     */
    showAlert: function () {
      var that = this
      this.alert.dismissCountDown = this.alert.dismissSecs
      for (let i = 0; i < that.alert.dismissSecs; i++) {
        (function () {
          setTimeout(() => that.alert.dismissCountDown--, 1000 * i)
        })()
      }
    },

    /**
     * @description:改变当前显示状态
     * @returns {void}
     */
    changeShow: function () {
      this.isShow = !this.isShow
    },

    /**
     * @description:获取通知列表数据
     * @returns {void}
     */
    getNoticeList: function () {
      var that = this
      this.$axios
        .get('/notice/list')
        .then(function (response) {
          that.data.notice = response.data
          // items备份
          that.colonData.notice = JSON.parse(JSON.stringify(that.data.notice))

          // 重置控制目标
          // that.selectedID = null
          // that.selected = null
        })
    },

    /**
     * @description:获取报道列表数据
     * @return
     */
    getReportList: function () {
      var that = this
      this.$axios
        .get('/report/list')
        .then(function (response) {
          that.data.report = response.data
          // items备份
          that.colonData.report = JSON.parse(JSON.stringify(that.data.report))

          // 重置控制目标
          // that.selectedID = null
          // that.selected = null
        })
    },

    /**
     * @description:获取文化列表数据
     */
    getCultureList: function () {
      var that = this
      this.$axios
        .get('/culture/list')
        .then(function (response) {
          that.data.culture = response.data
          // items备份
          that.colonData.culture = JSON.parse(JSON.stringify(that.data.culture))

          // 重置控制目标
          // that.selectedID = null
          // that.selected = null
        })
    },

    /**
     * @description:获取关键地点
     * @returns {void}
     */
    getKeyPoint: function () {
      var that = this
      this.$axios
        .get('/admin/keypoint')
        .then(res => {
          res.data.forEach(item => {
            that.places.push(item.name)
          })
        })
    },

    /**
     * @description:设置当前选择节点的状态,并地图响应
     * @param {event} e:事件
     * @param {number} index:所操作节点数据的下标
     */
    selectItem: function (e, index) {
      this.toolShow.delete = true
      let el = e.srcElement
      this.selected = el
      this.selectedIndex = index

      //  地图响应,绘制标识
      window.setTimeout(() => {
        this.printMapMarkByID()
      }, 500)
    },

    /**
     * @description:应用更改 响应事件
     */
    submitChange: function () {
      var that = this

      //  向后端提交删除信息，并根据成功与否作出回应
      this.postDelete()
        .then(res => {
          if (res) {
            //  重新获取table数据
            that.getNoticeList()

            //  初始化预删除数据
            that.deleteArr = []

            // alert 内容
            that.alert.message = '应用更改成功'
            that.alert.type = 'success'
          } else {
            // alert 内容
            that.alert.message = '应用更改失败'
            that.alert.type = 'danger'
          }
          window.setTimeout(function () {
            that.showAlert()
          }, 300)
        })
    },

    /**
     * @description:将预删除数据提交给后端进行数据库操作
     * @returns {void}
     */
    postDelete: async function () {
      var that = this
      var isSuccess = false
      await this.$axios
        .post('/admin/delete', {
          array: that.deleteArr
        })
        .then(res => {
          isSuccess = res.data
        })
      return isSuccess
    },

    /**
     * @description:在table中删除消息，并提交到预删除数据中等待提交更改
     * @returns {void}
     */
    deleteItem: function () {
      var items = this.tabIndex === 0 ? this.data.notice : this.data.report
      var itemsType = this.getSelectedType()
      // var itemsType = this.tabIndex === 0 ? 'notice' : 'report'

      // 将元素信息提交到预删除数组中，等待提交更改
      this.deleteArr.push({type: itemsType, id: items[this.selectedIndex].id})

      // 按序号在table显示数据中删除该消息
      items.splice(this.selectedIndex, 1)

      // 更新下标
      // 1.删除末尾元素时，更新下标重新指向末尾
      // 2.删除非末尾元素时,下标不变
      this.selectedIndex = this.selectedIndex === items.length ? this.selectedIndex - 1 : this.selectedIndex
    },

    /**
     * @description:放弃更改响应事件：初始化预删除数据，恢复table显示数据
     * @returns {void}
     */
    giveupChange: function () {
      this.data = JSON.parse(JSON.stringify(this.colonData))
      this.deleteArr = []
    },

    /**
     * @description:将目前所选取事件的id值与type值传给map.vue进行标识绘制
     * @returns {void}
     */
    printMapMarkByID: function () {
      bus.$emit('printMapMark', {
        type: this.getSelectedType(),
        id: this.getSelectedItems()[this.selectedIndex].id
      })
    },

    /**
     * @description:根据tabIndex 获取当前操作的Data数据属性
     * @returns {object}
     */
    getSelectedItems: function () {
      var item
      var data = this.data
      switch (this.tabIndex) {
        case 0:
          item = data.notice
          break
        case 1:
          item = data.report
          break
        case 2:
          item = data.culture
      }
      return item
    },

    /**
     * @description:根据tabIndex值 获取目前操作的数据类型
     */
    getSelectedType: function () {
      var res
      switch (this.tabIndex) {
        case 0:
          res = 'notice'
          break
        case 1:
          res = 'report'
          break
        case 2:
          res = 'culture'
          break
        default:
          res = null
      }
      return res
    },

    /**
    * @description: addModel提交(submit)事件
    * @returns {void}
     */
    submit_addModal: async function () {
      var that = this

      // 向后端提交表单
      this.postAddForm()
        .then(res => {
          if (res) {
            //  提交成果
            that.alert.message = '消息发布成功'
            that.alert.type = 'success'
            that.$bvModal.hide('addModal')
          } else {
            that.alert.message = '消息发布失败'
            that.alert.type = 'danger'
          }
          window.setTimeout(function () {
            that.showAlert()
          }, 300)

          //  刷新
          that.refresh()
        })
    },

    /**
     * @description:向后端提交消息发布的表单
     * @returns {void}
     */
    postAddForm: async function () {
      var that = this
      var isSuccess = false
      await this.$axios
        .post('/admin/add', {
          form: that.form
        })
        .then(res => {
          isSuccess = res.data
        })
      return isSuccess
    },

    /**
    * @description: loginModel提交(submit)事件
    * @returns {void}
     */
    submit_loginModal: function (e) {
      var that = this
      this.postLoginForm()
        .then(res => {
          if (res) {
            // 登陆成功，设置登陆状态
            that.$store.commit('userLogin', {
              name: res.name,
              uid: res.uid
            })
            // 设置token到cookie
            console.log(res.token)
          } else {
            that.login.isRight = false
          }
        })
    },

    /**
     * @description:向后端提交登陆表单
     * @returns {void}
     */
    postLoginForm: async function () {
      var response

      await this.$axios
        .post('admin/login', {
          form: {
            account: this.login.account,
            password: this.login.password
          }
        })
        .then(res => {
          response = res.data
        })
      return response
    },

    /**
     * @description:刷新列表，地图
     * @returns {void}
     */
    refresh: function () {
      this.getNoticeList()
      this.getReportList()
    }

  },
  mounted () {
    this.getNoticeList()
    this.getReportList()
    this.getCultureList()
    this.getKeyPoint()
  },
  watch: {
    /**
     * @description：每变换一次状态，更新一次地图尺寸
     * @param {DOM} newOne:新值
     * @param {DOM} oldOne:旧值
     */
    isShow (newVa, oldVa) {
      bus.$emit('updateMapSize')
    },

    /**
     * @description：每切换一次tab，重置选择状态
     * @param {DOM} newOne:新值
     * @param {DOM} oldOne:旧值
     */
    tabIndex (newVa, oldVa) {
      this.selectedIndex = -1
      this.selected = null
    },

    /**
     * @description:选择的节点发生改变时，颜色变化
     * @param {DOM} newOne:新值
     * @param {DOM} oldOne:旧值
     */
    selected (newOne, oldOne) {
      // 如果选择的<td>节点不变，不作更改
      // 否则 消除旧节点的颜色，修改新节点的颜色
      if (newOne === oldOne) {
        return 0
      } else {
        if (oldOne === null) {
          // 旧值为空
          newOne.style.background = '#b8daff'
        } else if (newOne === null) {
          // 新值为空
          oldOne.style.background = ''
        } else {
          // 都不为空
          oldOne.style.background = ''
          newOne.style.background = '#b8daff'
        }
      }
    },

    /**
     * @description:下标小于0时(空元素状态)，禁止删除操作
     * @param {DOM} newOne:新值
     * @param {DOM} oldOne:旧值
     */
    selectedIndex (newOne, oldOne) {
      if (newOne < 0) {
        this.toolShow.delete = false
      } else {
        this.toolShow.delete = true
        switch (this.tabIndex) {
          case 0:
            bus.$emit('markerShow', {
              type: this.tabIndex,
              id: this.data[this.tabIndex]
            })
        }
      }
    },

    /**
     * @description:监听预删除数据，当其不为空时使得‘应用更改’按钮可用
     * @param {DOM} newOne:新值
     * @param {DOM} oldOne:旧值
     */
    deleteArr (newOne, oleOne) {
      if (newOne.length > 0) {
        this.toolShow.submit = true
      } else {
        this.toolShow.submit = false
      }
    },

    /**
     * @description:监听备份数据，发生改动意味着发生数据库操作，刷新地图数据
     * @param {DOM} newOne:新值
     * @param {DOM} oldOne:旧值
     */
    colonItems (newOne, oldOne) {
      bus.$emit('refreshMap')
    }
  },
  filters: {
    // 超过16位显示省略号
    ellipsis: function (value) {
      if (!value) return ''
      if (value.length > 10) {
        return value.slice(0, 10) + '...'
      }
      return value
    }
  }
}
</script>
<style scoped>
  .close{
    float: right;
  }
  #list {
    width: 310px;
    height: 100%;
    display: flex;
  }
  .listGroup {
    font-size:14px
  }
  #header {
    background: rgba(222,226,230,0.5)
  }
  #body {
    flex:1
  }
  #footer{
    background: rgba(222,226,230,0.5);
  }
  .logo {
    width: 32px;
    height:32px
  }
  #btn{
    position:absolute;
    right:10px;
    top:10px;
    z-index: 10;
    float:right;
  }
  #alert {
    position: absolute;
    top:0px;
    width:100%;
    z-index:10000
  }

</style>
