<!--
 * @Author: your name
 * @Date: 2021-01-18 15:46:34
 * @LastEditTime: 2021-11-30 18:54:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3-element-admin\src\views\Home.vue
-->
<template>
  <div class="container2">
    <div class="mainDiv">
      <Nslb @selectNsItem="selectNsItem" ref="nslbRef" :key="nslbUpdate" class="leftBox"></Nslb>
      <div class="rightBox">
        <div class="head">
          <div class="item1">
            <div class="warning"></div>
            <div class="warning"></div>
            <div class="warning"></div>
            <template v-if="day > 0">
              执行时间还剩<font style="color:#ffffff;">{{day}}</font>天
            </template>
            <template v-if="day < 0">
              农事任务已经开始<font style="color:#ffffff;">{{-day}}</font>天
            </template>
            <template v-if="day == 0">
              执行时间就在今天
            </template>
          </div>
          <div class="item2">
            <font style="color:#ffffff;">执行区域：</font>
            <template v-for="(item,index) in areaArr">
              <template v-if="index != 0">、</template>{{item.name}}
            </template>
            <template v-if="execStyle">
              <font style="color:#ffffff;">执行方式：</font>{{execStyle == 1 ?'无人机':'人工'}}
            </template>
          </div>
        </div>
        <div class="map" ref="mapRef"></div>
        <div class="foot">
          <div class="row">工人分配详情
            <el-button v-if="nsRecordStatus == STARUS_ENUM.STAY_SEND"
                       size="large"
                       color="#03232d"
                       class="submit"
                       @click="submit"
                       type="primary" >确定下发</el-button>
          </div>
          <template v-for="item in areaArr" :key="item.id">
            <div class="row">
              {{item.name}}({{areaTreeCountMap[item.id].count}}棵树）责任人：
              <select class="select" @change="changeWorkerTel(item.id)"
                      :disabled="nsRecordStatus != STARUS_ENUM.STAY_SEND"
                      v-model="allotMap[item.id].workerTel">
                <option  value="" >请选择</option>
                <option v-for="item in workerList" :key="item.tel"  :value="item.tel" >{{item.name}}</option>
              </select>
              <font class="font2">(建议人数5)</font>
            </div>
            <div class="row">
              <div class="item" v-for="item in allotMap[item.id].executorList" :key="item.executor">
                {{item.name}}
                <div v-if="nsRecordStatus == STARUS_ENUM.STAY_SEND"  class="close cursor-pointer"
                     @click="removeExecutor(item)">x</div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>

</template>

<script setup>
import {useStore} from "vuex"
import { ElMessage,ElMessageBox  } from 'element-plus'
import {onMounted, ref, reactive, toRefs, provide, inject , watch, computed} from "vue";
import config from "@/api/config.js"
import {NS_RECORD_STATUS_ENUM as STARUS_ENUM} from "../../api/enum"
import {useRoute, useRouter} from "vue-router";
import {dateFormat,GetDateDiff} from "../../utils/date_util"
import Title from "../components/title";
import AllotNsMap from "./AllotNsMap";
import Nslb from "./components/Nslb"

const emit = defineEmits(["back"])

const selectDateObj = ref({})

const router = useRouter();
const route = useRoute()
const nslbRef = ref(null)
const nsDrugList = ref([])
const nsTypeList = ref([])
const store = useStore()
const nslbUpdate = ref(1)
const location = store.getters.userinfo.location
const organId = store.getters.userinfo.curGardenId
const workerList = ref([])
const mapRef=ref(null)

const execDate = ref(null)
const treeIds = ref([])
const areaIds = ref([])
const execStyle = ref(null)
const areaTreeCountMap = ref({}) // 区树的数量map
const areaArr = ref([])//区的map
const day = ref(null)//

const nsRecordId = ref(null)
const nsRecordStatus = ref(null)
const allotMap = ref({})

const kmap = new AllotNsMap()
onMounted(()=>{
  initWorker()
  kmap.initMap(location, mapRef.value)
  kmap.addToggleAreaSelect()
  kmap.addToggleTreeSelect()
  kmap.initArea(organId, ()=>{
    kmap.initTree(organId, ()=>{
    })
  })
})

//重置选择
function resetSelectNsItem(){
  nsRecordId.value = null
  nsRecordStatus.value = null
  execDate.value =  []
  day.value = null
  treeIds.value = []
  areaIds.value = []
  areaArr.value = []
  execStyle.value = []
  nslbUpdate.value = nslbUpdate.value + 1
  loadSelectArea()
  loadSelectTree()
}

//选择农事
function selectNsItem(id){
  VE_API.nsjy.getNsRecord({id}).then(({data})=>{
    nsRecordId.value = id
    nsRecordStatus.value = data.status
    execDate.value = data.execDate ? data.execDate : []
    if(data.execDate && data.execDate.length > 0){
      day.value = GetDateDiff(new Date(), new Date(data.execDate[0]),"day")
    }
    treeIds.value = data.treeIds
    areaIds.value = data.areaIds
    execStyle.value = data.execStyle
    loadSelectArea()
    loadSelectTree()
    loadWorkerTels()
  })
}
//加载areaIds 数据选中
function loadSelectArea(){
  let arr = []
  kmap.areaLayer.toggleSelect.getFeatures().clear()
  if(areaIds.value == 0){
    return
  }
  kmap.areaLayer.source.forEachFeature((f)=>{
    let res = areaIds.value.find((id)=> f.get("id") == id)
    if(res){
      arr.push({id:f.get("id"),name:f.get("name")})
      allotMap.value[f.get("id")] = {id:"",workerTel:"",areaId:f.get("id"),nsRecordId: nsRecordId.value, executorList:[]}
      kmap.areaLayer.toggleSelect.getFeatures().push(f)
    }
  })
  areaArr.value = arr
}

function loadWorkerTels(){
  VE_API.ns_record_allot.list({nsRecordId:nsRecordId.value}).then(({data})=>{
    for(let key in allotMap.value){
      let obj = data.find((item)=> item.areaId == key)
      if(obj){
        allotMap.value[key] = obj
      }
    }
  })
}

//加载treeIds 数据选中
function loadSelectTree(){
  let i = 0
  kmap.treeLayer.toggleSelect.getFeatures().clear()
  if(!treeIds.value && treeIds.value.length == 0){
    return
  }
  let areaMap = {}
  kmap.treeFeatures.forEach((f)=>{
    while(i < treeIds.value.length){
      if(f.get("id") === treeIds.value[i]){
        if(areaMap[f.get("areaId")] == null){
          areaMap[f.get("areaId")] = {count:1}
        }else{
          areaMap[f.get("areaId")]["count"]++
        }
        kmap.treeLayer.toggleSelect.getFeatures().push(f)
        i++
      }
      break
    }
  })
  areaTreeCountMap.value = areaMap
}

function changeWorkerTel(areaId){
  let form = allotMap.value[areaId]
  VE_API.ns_record_allot.save(form).then(()=>{
    loadWorkerTels()
  })
}

function removeExecutor(item){
  VE_API.ns_record_allot_executor.remove({allotId: item.allotId, executor: item.executor}).then(({code})=>{
    if(code == 0)
      selectNsItem(nsRecordId.value)
  })
}

function submit(){
  VE_API.nsjy.sendStayExecute({id:nsRecordId.value, status: STARUS_ENUM.STAY_EXECUTE}).then(({code})=>{
    if(code == 0){
      nslbUpdate.value++
      resetSelectNsItem()
      nslbRef.value.reset()
    }
  })
}


function initWorker(){
  VE_API.garden_worker.list({organId:organId}).then(({data})=>{
    workerList.value = data
  })
}

</script>

<style lang="scss" scoped>
@import "../../styles/index.scss";
.container2{
  height: 100%;
  width: 100%;
  z-index: 2;
  position: absolute;
}
.mainDiv{
  position: absolute;
  top:100px;
  bottom: 50px;
  left: 20px;
  right: 20px;
  .leftBox{
    float: left;
    width: 500px;
    height: calc(100%);
  }
  .rightBox{
    float: right;
    width: calc(100% - 500px - 12px);
    height: 100%;
    background: #032C3940;
    border-radius: 4px;
    border: 1px solid rgba(81, 233, 240, 0.6);
    box-sizing: border-box;
    .head{
      margin: 19px 0px 0px 19px;
      @include wh(calc(100% - 19px - 19px),calc(40px));
      font-family: DOUYU;
      font-weight: normal;
      font-size: 22px;
      color: #FF5926;
      .item1{
        float: left;
        @include wh(489px,40px);
        @include ossBg("item1.png");
        display: flex;
        align-items: center;
        padding-left: 10px;
        .warning{
          @include wh(29px,25px);
          @include ossBg("warning.png");
        }
      }
      .item2{
        float: left;
        @include wh(489px,40px);
      }
    }
    .map{
      margin: 19px 0px 0px 19px;
      @include wh(calc(100% - 19px - 19px),calc(100% - 40px - 300px - 19px - 19px))
    }
    .foot{
      position: relative;
      margin: 19px 0px 0px 19px;
      @include wh(calc(100% - 19px - 19px),calc(300px));
      font-family: DOUYU;
      font-weight: normal;
      font-size: 22px;
      color: #FFFFFF;
      .submit{
        width: 200px;
        position: absolute;
        right: calc(100px);
        bottom: 50px;
      }
      .row{
        height: 39px;
        display: flex;
        align-items: center;
        .select{
          border-radius: 5px;
          text-align: center;
          width: 150px;
          background: rgba(10,236,255,0.21);
          color: #59EBFF;
        }
        .font2{
          font-family: PingFang SC;
          font-weight: 800;
          font-size: 22px;
          color: #FF5926;
          margin-left: 10px;
        }
        .item{
          position: relative;
          @include wh(100px,34px);
          background: #0AECFF;
          border-radius: 5px;
          border: 1px solid #59EBFF;
          margin-left: 18px;
          color: #023236;
          font-size: 16px;
          line-height: 34px;
          text-align: center;
          font-weight: bold;
          .close{
            position: absolute;
            right:-7px;
            top:-7px;
            @include wh(15px,15px);
            background: #FF5926;
            color: #ffffff;
            border-radius: 50%;
            text-align: center;
            line-height: 15px;
            font-size: 12px;
          }
        }
        .item:first-child{
          margin-left: 0px;
        }
      }
    }
  }
}

</style>
