<template>
  <div class="basic-main" style="height: 100%">
    <div class="row">
      <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="searchCondition.date"
                          v-model="searchCondition.date"
                          :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="searchCondition.userId" v-model='searchCondition.userId'
                        :value-single="true" clear-button search
                        :options='searchUserEndOption' placeholder='请选择'
              ></v-select>
            </div>
            <div class="col-sm-3 form-input-group" style="width: 20%">
              <label class="control-label">班组</label>
              <v-select :value.sync="searchCondition.departmentId" v-model='searchCondition.departmentId'
                        :value-single="true" clear-button search
                        :options='searchDepartmentOption' placeholder='请选择'
              ></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>
        <a-map-trajectory-new :outerlinedata.sync="outerlinedata" :pathnavigatorstyle="pathnavigatorstyle" :dom="dom"></a-map-trajectory-new>
      </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; height: 700px">
                <accordion :one-at-a-time="true" v-if="reponData.length>0">
                  <template v-for="row in reponData">
                    <panel is-open="false"  type="primary"  @click="chengeLocation(row)">
                      <strong slot="header">人员姓名：{{row.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 * as Util from '../Util'
import {HttpResetClass} from 'vue-client'
import { douglasPeuckerForAMap } from './douglasPeuckerForAMap'

export default {
  title: "安检员轨迹展示",
  data() {
    return {
      showTaskPoints: [],
      taskModel: {},
      //  当前分公司下所有的用户id
      toUserIds: '',
      // 当前公司的所有安检员
      searchUserEndOption: [],
      searchDepartmentOption: [],
      // 请求到的结果集合
      reponData: [],
      // 点集
      outerlinedata: [],
      pathnavigatorstyle: {
        // 图标宽度
        width: 16,
        // 图标高度
        height: 32,
        // 图标地址（外链地址或者Base64）
        iconBase64: 'https://webapi.amap.com/ui/1.1/ui/misc/PathSimplifier/examples/imgs/car.png'
      },
      // 分公司ids
      f_filialeids: '',
      path: [],
      aMap: null,
      map: null,
      filialeOptions: [],
      userid: null,
      dom: 'amapIdLOCUS' + Math.round(Math.random() * 10) + Math.round(Math.random() * 10),
      rootSubmenuKeys: ['1', '2'],
      openKeys: ['1'],
      searchCondition: {
        condition: '1 = 1',
        orderTime: 'ps.f_realtime asc',
        date: '',
        userId: undefined,
        departmentId: undefined
      }
    }
  },
  methods: {
    chengeLocation(row) {
      const points = douglasPeuckerForAMap(row.points, 2, 'tm')
      this.outerlinedata = [{ path: points, speed: Math.ceil(points.length / 2), name: `${this.searchCondition.date}的轨迹` }]
    },
    search() {
      var condition = '1 = 1'
      if (!this.f_filialeids) {
        return this.$showMessage('请选择需要查询的分公司')
      }
      if (!this.searchCondition.date) {
        return this.$showMessage('请选择需要查看的轨迹时间')
      }
      // if (!this.searchCondition.userId[0]) {
      //   return this.$showMessage('请选择需要查看的轨迹所属人员')
      // }

      if (typeof this.searchCondition.date !== 'string') {
        this.searchCondition.date = this.searchCondition.date.format('YYYY-MM-DD')
      }
      condition += " and ps.f_realtime >= '" + this.searchCondition.date + " 00:00:00' and ps.f_realtime <= '" + this.searchCondition.date + " 23:59:59'"
      if(this.searchCondition.userId){
        condition += ` and ps.f_user_id = '${this.searchCondition.userId}'`
      }
      let condition2 = '1 = 1'
      if(this.searchCondition.departmentId){
        condition2 += ` and d.id = '${this.searchCondition.departmentId}'`
      }
      this.searchCondition.condition = condition
      this.$resetpost('rs/logic/getPhoneState', { condition: this.searchCondition.condition, condition2, orderTime: this.searchCondition.orderTime }, {resolveMsg: "轨迹记录查询成功", rejectMsg: "轨迹记录查询失败"}).then((response)=>{
        if (response.data.state === 'success') {
          this.reponData = response.data.result
          // const points = douglasPeuckerForAMap(response.data.result, 2, 'tm')
          // this.outerlinedata = [{ path: points, speed: Math.ceil(points.length / 2), name: `${this.searchCondition.date}的轨迹` }]
        } else {
          this.$showMessage("该用户当日使用app时间较短或行程较少,不足够生成轨迹")
        }
      })
    },
    getRes(obj){
      // this.model.f_filialeids = this.$login.convertToIn(obj.resids);
      if (obj.res != undefined && obj.res.length > 0 && obj.res[0] != undefined) {
        this.getNewData(obj.res[0])
      }
      this.f_filialeids = this.$login.convertToIn(obj.resids);
    },
    //获取定位人员类表
    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 = [{label:'全部',value:''}]
      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

      let resp = await new HttpResetClass().load('POST', `/rs/sql/safe_singleTable_OrderBy`, {
        data: {
          items:'*',
          tablename: 't_department',
          condition: `parentid = '${this.$login.f.orgid}' and f_dep_type = '部门'`,
          orderitem:'id'
        }
      }, {resolveMsg: null, rejectMsg: null})
      //tag)
      const departments = [{label: '全部', value: ''}]
      for (const item of resp.data) {
        departments.push({
          label: item.name,
          value: item.id
        })
      }
      this.searchDepartmentOption = departments
    },
    toStandardDateString () {
      const dt = new Date()
      const month = dt.getMonth() + 1
      const date = dt.getDate()
      return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
    }
  },
  ready(){
    this.searchCondition.date = this.toStandardDateString()
  }
}
</script>

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