<template>
  <div class="basic-main" style="height: 100%">
    <div>
      <div class="col-sm-9 amap-main" >
        <div class="form-horizontal select-overspread container-fluid auto">
          <div class="row">
            <div class="col-sm-3 form-input-group" style="width: 20%">
              <label class="control-label">公&emsp;&emsp;司</label>
              <right-tree-safe @re-res="getRes"  >
              </right-tree-safe>
            </div>
            <div class="col-sm-3 form-input-group" style="width: 20%">
              <label class="control-label" >轨迹时间</label>
              <datepicker placeholder="轨迹时间"
                          :value.sync="requestData.chengeDate"
                          v-model="requestData.chengeDate"
                          :format="'yyyy-MM-dd'">
              </datepicker>
            </div>
            <div class="col-sm-3 form-input-group" style="width: 20%">
              <label class="control-label">安检员</label>
              <v-select :value.sync="selUserIds" v-model='selUserIds'
                        :value-single="false" clear-button search multiple
                        :options='searchUserEndOption' placeholder='安检员'
              ></v-select>
            </div>
            <div class="col-sm-3 form-input-group" style="width: 20%">
              <label class="control-label">网格员</label>
              <v-select class="select_list select"
                        placeholder='请选择' style="width: 60%"
                        :value.sync="requestData.f_book_checker" v-model="requestData.f_book_checker"
                        :options='users'
                        filer-key="name"
                        close-on-select clear-button
                        :value-single="true">
              </v-select>
            </div>
            <div class="col-sm-3 form-input-group" style="width: 20%;float:right;">
              <button class="btn btn-primary"  @click="search">查询</button>
            </div>
          </div>
        </div>
        <amap-trajectory :outerlinedata.sync="outerlinedata" :pathnavigatorstyle="pathnavigatorstyle" ></amap-trajectory>
      </div>
      <div class="col-sm-3">
        <div id="zzz" class="basic-main" style="flex:1;margin-left: 0px;overflow: hidden">
          <div class="flex">
            <div class="panel panel-info" style="flex: 4;margin-top:0px;height: 50%">
              <div class="panel-heading" style="height: auto">
                <h3 class="panel-title">轨迹记录</h3>
              </div>
              <div class="panel-body" style="overflow: scroll">
                <accordion :one-at-a-time="true" v-if="reponData.length>0">
                  <template v-for="row in reponData">
                    <panel is-open="false"  type="primary">
                      <strong slot="header">用户编号:{{row.f_user_id}} 用户姓名：{{row.f_user_name}}</strong>
                      <div v-for="(idx,item) in row.result" @click="chengeLocation(item)"  :class="{'alert alert-info':idx%2===0,'alert alert-success':idx%2!==0}">
                        轨迹时间段：{{item.f_start_date}} ~ {{item.f_end_date}}
                      </div>
                    </panel>
                  </template>
                </accordion>
                <h4 class="panel-title" v-else>暂无相关数据</h4>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import co from 'co'
import * as Util from '../../Util'
import {HttpResetClass} from 'vue-client'

/**
 * 1. 首先获取当前选择的分公司下所有带定位角色的所有用户
 * 2. 根据查询出来的所有用户的id和选择的时间去轨迹表查询，获取具体轨迹的时间段
 * 3. 渲染给前台页面，前台根据选择的用户和时间端获取轨迹信息去渲染轨迹，每次只可以渲染一组轨迹
 */


export default {
  title: "安检员轨迹展示",
  data() {
    return {
        toUserIds: '', //当前分公司下所有的用户id
        selUserIds:[], // 当前选择的用户Id
        requestData: {
          chengeDate: Util.toStandardDateString(),
          f_book_checker:'',
          userIds: '',
        },
        searchUserEndOption: [], //当前公司的所有安检员
        reponData: [], // 请求到的结果集合
        outerlinedata: [], //点集
      users:[{label: '全部', value: ''}],
      pathnavigatorstyle: {
          width: 16, //图标宽度
          height: 32, // 图标高度
          iconBase64: 'https://webapi.amap.com/ui/1.1/ui/misc/PathSimplifier/examples/imgs/car.png'//图标地址（外链地址或者Base64）
        },
        f_filialeids: '', //分公司ids
        path: [],
    }
  },
  methods: {
    initBookChecker(){
      new HttpResetClass().load('POST', '/rs/search', {
        data: {
          source: `root.getResourceById($${this.$login.f.orgid}$,$organization$).getSpecialResByType($user$).where(row.getAttributes().get($rolestr$).indexOf($网格员$) != -1)`,
          userid: this.$login.f.id
        }
      }, {resolveMsg: null, rejectMsg: null}).then(res=>{
        let data = res.data
        const addedNames = new Set()
        this.users = []
        data.forEach(user => {
          if (user.state === '在职') {
            if (!addedNames.has(user.name)) {
              this.users.push({label:user.name,value:user.id})
              addedNames.add(user.name)
            }
          }
        })
        console.log(this.users)
      })
    },
    search() {
        if (this.selUserIds.length==0&&!this.requestData.userIds) {
          this.requestData.userIds = this.toUserIds
        }
        if (this.requestData.f_book_checker){
          const content = this.requestData.userIds.slice(1, -1)
          const elements = content.split(',')
          elements.push(`'${this.requestData.f_book_checker}'`)
          this.requestData.userIds = `(${elements.join(',')})`
        }
        if (!this.f_filialeids) {
          return this.$showMessage("请选择需要查询的分公司")
        }
        if (!this.requestData.chengeDate) {
          return  this.$showMessage("请选择需要查看的轨迹时间")
        }
        this.$resetpost('rs/logic/QueryUserTracksByCompany',this.requestData,{resolveMsg: "轨迹记录查询成功", rejectMsg: "轨迹记录查询失败"}).then((response)=>{
          if (response!=undefined && response.data.code == 200) {
              this.reponData = response.data.data
          }else if (response!=null && response.data.code == 404) {
              this.reponData = []
            this.$showMessage("未查询到当前用户的相关轨迹信息")
          } else if (response!=null && response.data.code == 555) {
            this.$showMessage("查询轨迹信息错误！错误原因:"+response.data.msg)
          }
        })
    },
    getRes(obj){
      // this.model.f_filialeids = this.$login.convertToIn(obj.resids);
      console.log(obj)
      if (obj.res != undefined && obj.res.length > 0 && obj.res[0] != undefined) {
        this.getNewData(obj.res[0])
        this.initBookChecker(obj.res[0])
      }
      this.f_filialeids = this.$login.convertToIn(obj.resids);
    },
    chengeLocation(row) {
      console.log(row)
      this.$resetpost('rs/logic/queryRemoteLocationMapData',{data:{id:row.id}},{resolveMsg: "查询渲染轨迹成功", rejectMsg:"查询渲染轨迹失败！"}).then((response)=>{
        if (response!=undefined && response.data!=undefined) {
            this.path = response.data
            let name = `${row.f_user_name},${row.f_start_date}~${row.f_end_date}轨迹`
            this.outerlinedata = [{path:this.path,speed:Math.ceil(this.path.length / 2),name:name}]
        }
      })
    },
    //获取定位人员类表
    async getNewData(organization){
      // let organization = '公司名称'
      // let userRolestr  = '需要定位人员'
      let userRolestr  = '安检员'
      let res =await new HttpResetClass().load('POST', '/rs/search', {
        // source: 'this.getParentByType($department$).getAllChildrens().where(row.getAttributes().get($rolestr$).indexOf($需要定位人员$) != -1))',
        source: "this.getParentByName($"+organization+"$).getAllChildrens().where(row.getAttributes().get($resourcetype$)==$user$).where(row.getAttributes().get($rolestr$)!=null).where(row.getAttributes().get($rolestr$).indexOf($"+userRolestr+"$)!=-1)",
        userid: this.$login.f.id
      }, {resolveMsg: null, rejectMsg: null})
      let dataEnd = [];
      let idsEnd = [];
       res.data.forEach(res=>{
         let h=true
         dataEnd.forEach(per=>{
           if(res.id==per.value){
             h=false
           }
         })
         if(h){
           dataEnd.push({label:res.name,value:res.id})
           idsEnd.push(res.id)
         }
       })
      this.toUserIds = this.$login.convertToIn(idsEnd); //所有的员工ID
      this.searchUserEndOption = dataEnd
    },
  },
  ready(){
    this.initBookChecker()
  },
  watch: {
    'selUserIds':function (val) {
      if (val=='') {
        this.requestData.userIds = ''
      }else {
        this.requestData.userIds = this.$login.convertToIn(val)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.amap-main {
  height: 90%;
  padding-right:10px;
}
</style>
