 <template>
  <div class="app-container">
    <div class="search">
      <el-time-picker v-model="table.parammaps.date" style="width: 250px;" value-format="HH:mm:ss" />
      <el-input v-model="table.parammaps.eqCode" placeholder="车辆编码" style="width: 180px;" class="filter-item" clearable />
      <!-- <el-select v-model="table.getdataListParm.parammaps.enable" filterable placeholder="是否启用" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in enableList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select> -->
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
      <el-button class="successBorder" @click="form_search">查询</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isRoleEdit" class="success" icon="el-icon-plus" style="float: left;" @click="handleCreate">新增</el-button>
    </div>
    <div class="table">
      <el-table
        :key="table.tableKey"
        ref="table"
        v-loading="table.listLoading"
        element-loading-text="给我一点时间"
        :data="table.list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable table-fixed"
        @selection-change="handleSelect"
        :max-height="myHeight"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column :key="1" label="序号" align="center" type="index" width="50px" class-name="small-padding fixed-width" fixed="left" />
        <el-table-column label="推料车" min-width="100px" align="center" class-name="small-padding fixed-width" fixed="left" prop="tname" />
        <el-table-column label="时间" min-width="100px" align="center" prop="date" />
        <el-table-column label="备注" min-width="100px" align="center" prop="remark" />
        <el-table-column label="栏舍" min-width="100px" align="center" prop="bname" />
        <el-table-column label="状态" min-width="90px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" :disabled="scope.row.NoEdit==true" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEnableChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="isRoleEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleRunning_trajectory(row)" />
            <el-button v-if="isRoleEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
            <el-button v-if="isRoleEdit" class="miniDanger" icon="el-icon-delete" @click="handleRowDelete(row)" />
          </template>
        </el-table-column>
      </el-table>
      <span v-if="table.listLoading == false" style="margin-right: 30px;margin-top: 10px;font-size: 14px;">共{{ table.total }}条</span>
    </div>
     <el-dialog :fullscreen="dialogFull" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="50%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            推料计划
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-add">
        <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="155px" style="width: 100%;margin:0 auto 50px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="推料车：" prop="tmrId">
                <el-select v-model="create.temp.tmrId" filterable placeholder="推料车" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in tmrList" :key="item.id" :label="item.tname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="时间：" prop="date">
                <el-time-picker v-model="create.temp.date" style="width: 100%;" value-format="HH:mm:ss" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input ref="remark" v-model="create.temp.remark" class="filter-item" placeholder="备注" type="text" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="栏舍：" prop="barId">
                <el-select v-model="create.temp.barId" multiple  filterable placeholder="栏舍" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in barList" :key="item.id" :label="item.bname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态：" prop="enable">
                <el-switch v-model="create.temp.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"  />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;getList()">关闭</el-button>
          <el-button class="save" @click="create.dialogStatus = 'create' ? createData():updateData()" :disabled="isokDisable" >确认</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog  :visible.sync="run.dialogFormVisible" :close-on-click-modal="false" width="50%">
     <template slot="title">
       <div class="avue-crud__dialog__header">
         <span class="el-dialog__title">
           <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
           运行轨迹
         </span>
         <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
           <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
           <svg-icon v-else icon-class="fullscreen" />
         </div>
       </div>
     </template>
    <div ref="map" class="map-container"></div>
    <div slot="footer" class="dialog-footer">
       <el-button class="cancelClose1" @click="run.dialogFormVisible = false;getList()">关闭</el-button>
    </div>
   </el-dialog>

  </div>
</template>

<script>
import { GetDataByName, postJson,getJson, formatNum, checkButtons } from '@/api/common'
import { parseTime} from '@/utils/index.js'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { createApp } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
  securityJsCode: '0133db0118e961029dc45a2d5039cbb1' // '「申请的安全密钥」',
}
export default {
  name: 'PushMaterialPlan',
  data() {
    return {
      table: {
        parammaps: {
          pastureid: Cookies.get('pastureid'),
          date:'',
          eqCode:''
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
      },
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: { pastureId: Cookies.get('pastureid'), tmrId: '',date: '',remark: '',barId: '',enable: ''},
        rules: {
          tmrId: [{ required: true, message: '必填', trigger: 'blur' }],
          date: [{ required: true, message: '必填', trigger: 'blur' }],
          remark: [{ required: true, message: '必填', trigger: 'blur' }],
          barId: [{ required: true, message: '必填', trigger: 'blur' }],
          enable: [{ required: true, message: '必填', trigger: 'blur' }]
        }
      },
      run: {
        dialogFormVisible: false,
        dialogStatus: '',
      },
      dialogFull: false,
      tmrList:[],
      barList:[],
      isRoleEdit: [],
      selectList: [],
      isokDisable: false,
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      myHeight: document.documentElement.clientHeight - 85- 150,
       map: null,
      path: [
        [116.405285, 39.904989], // 示例轨迹点1
        [116.407516, 39.904717], // 示例轨迹点2
        [116.407366, 39.91344],  // 示例轨迹点3
        // 添加更多轨迹点
      ],
      index: 0,
    }
  },
   mounted() {
      // this.initMap();
    },
  created() {
    this.getButtons()
    this.getTMR_barList()
    this.getList()

  },

  methods: {
    getButtons() {
      const Edit = 'DhedFormula'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    getTMR_barList() {
      let url = '/authdata/GetDataByName'
      let data = {
        name: 'getTMRList', page: 1, offset: 1,
        parammaps: {
          pastureid: Cookies.get('pastureid'),eqtype:'1'
        }
      }
      postJson(url,data).then(response => {
        if (response.data.list !== null) {
          this.tmrList = response.data.list
        } else {
          this.tmrList = []
        }
      })
      let url2 = '/authdata/GetDataByName'
      let data2 = {
        name: 'getBarList', page: 1, offset: 1,
        parammaps: {
          pastureid: Cookies.get('pastureid')
        }
      }
      postJson(url2,data2).then(response => {
        if (response.data.list !== null) {
          this.barList = response.data.list
        } else {
          this.barList = []
        }
      })
    },
    getList() {
      this.table.listLoading = true
      let url = '/authdata/tmrequipment'
      let data = '?pastureId='+ Cookies.get('pastureid') +'&offset=1' + '&page=50'+'&date='+this.table.parammaps.date +'&eqCode='+this.table.parammaps.eqCode
      getJson(url,data).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.table.list = response.data.data
        } else {
          this.table.list = []
        }
        this.table.total = response.data.count
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
     // 新增
    handleCreate() {
      this.resetTemp()
      this.dialogFull = false
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
    },
    resetTemp() {
      this.create.temp.tmrId = ''
      this.create.temp.pastureId = Cookies.get('pastureid')
      this.create.temp.date = ''
      this.create.temp.remark = ''
      this.create.temp.barId = ''
      this.create.temp.enable = 1
    },
    createData(){
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          let url = '/authdata/tmrequipment/edit'
          let data = this.create.temp
          data.barId = this.create.temp.barId.join()
          // data.date = parseTime(this.create.temp.date,'{h}:{i}:{s}')
          postJson(url,data).then(response => {
            if(response.msg == 'fail'){
              this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
            }else{
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    // 编辑
    handleUpdate(row) {
      this.create.temp = Object.assign({},row)
      this.create.temp.barId = row.barId.split(',')
      this.dialogFull = false
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
    },
    updateData(row) {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          let url = '/authdata/tmrequipment/edit'
          let data = this.create.temp
          data.barId = this.create.temp.barId.join()
          // data.date = parseTime(this.create.temp.date,'{h}:{i}:{s}')
          postJson(url,data).then(response => {
            if(response.msg == 'fail'){
              this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
            }else{
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    handleRowDelete(row){
      let url = '/authdata/tmrequipment/del'
      let data = {}
      data.id = row.id
      postJson(url,data).then(response => {
        if(response.msg == 'fail'){
          this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
        }else{
          this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
          this.getList()
        }
      })
    },
    handleSelect(val) {
      console.log('勾选数据', val)
      this.selectList = val
    },
    handleEnableChange(index,row) {
      console.log('点击了是否启用')
      let url = '/authdata/tmrequipment/edit'
      let data = row
      // data.barId = row.barId.join()
      // data.date = parseTime(this.create.temp.date,'{h}:{i}:{s}')
      postJson(url,data).then(response => {
        if(response.msg == 'fail'){
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        }else{
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.create.dialogFormVisible = false
          this.getList()
        }
      })
    },

    form_search() {
      console.log('点击了查询')
      this.getList()
    },
    handleRefresh(){
      this.table.parammaps.date = ''
      this.table.parammaps.eqCode = ''
    },
    handleRunning_trajectory(row){
      console.log('点击了运行轨迹')
      this.run.dialogStatus = 'run'
      this.run.dialogFormVisible = true
      // let arr = [{"A":"4052.72555","N":"11312.94319"},{"A":"4052.725552","N":"11312.943192"}]
      // let arrList = []
      // for(let i=0;i<arr.length;i++){
      //   let list = []
      //   list.push(arr[i].A,arr[i].N)
      //   arrList.push(list)
      // }
      // console.log(arrList,'arrList')
      this.initMap();
    },
    async initMap() {
      await AMapLoader.load({
        key: 'fb6a0e88dbad4931d96a121bcf7c4442', // 替换为你的高德地图API Key
        version: '2.0',
        plugins: [],
      });

      this.map = new window.AMap.Map(this.$refs.map, {
        zoom: 13,
        center: this.path[0],
      });

      this.drawPath();
      this.drawDrop();
      // this.startLoop();
    },
    drawPath() {
      const polyline = new window.AMap.Polyline({
        path: this.path,
        strokeStyle: 'red',
        strokeColor: '#3366FF',
        strokeOpacity: 1,
        strokeWeight: 3,
        map: this.map,
        dirArrowStyle: true
      });
      // 调整地图视图以适应轨迹
      this.map.setFitView();
    },
    drawDrop(){
      var that = this
      that.path.forEach(function(coord, index) {
          var marker = new AMap.Marker({
              position: coord, // 对应点的经/纬度
              map: that.map, // 显示在地图上
              icon: new AMap.Icon({
                // size: new AMap.Size(36, 36),  // 图标尺寸
                image: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b'+ (index + 1) +'.png',  // 自定义图标
                // imageSize: new AMap.Size(36, 36),  // 图标尺寸
              }),
              offset: new AMap.Pixel(-10, -30) // 调整图标的偏移，使图标中心显示在点位置
          });
          // var label = new AMap.Text({
          //     text: (index + 1).toString(), // 显示的数字
          //     position: coord, // 标签位置与点位置相同
          //     offset: new AMap.Pixel(-10, -20), // 调整标签的偏移，使数字显示在点的正上方
          //     map: that.map // 显示在地图上
          // });
          // 添加信息窗体
          marker.on('click', function() {
              var infoWindow = new AMap.InfoWindow({
                  content: '经度：' + coord[0] + '<br>纬度：' + coord[1]
              });
              infoWindow.open(that.map, marker.getPosition());
          });
      });
    }
  }
}
</script>
<style lang="scss" scoped>
  .map-container {
    height: 400px;
  }
  .search {
    clear: both;
  }

  .table {
    margin-top: 10px;
  }
  .el-tag{margin-right: 5px;}
</style>
<style lang="scss">
  .red-row{
    background: #fde2e2 !important;
  }
</style>
