<template>
  <el-drawer
    title="任务分配"
    :visible.sync="visible"
    :direction="direction"
    class="allotTasks"
    :size="drawerWidth"
    :before-close="handleClose">
    <el-form ref="dialogForm" :model="ruleForm" size="medium" label-width="120px">
      <el-tag class="bt-tag" style="margin-bottom: 15px" effect="dark">任务详情</el-tag>
      <el-form-item label-width="70px" label="任务分类">
        <el-tag class="bt-tag" style="margin-left: 10px" :key="index" v-for="(item,index) in getTypeText"
                effect="plain">{{item.typeText}}
        </el-tag>
      </el-form-item>
      <el-table stripe style="margin-top: 10px;margin-bottom: 15px" v-loading="mainTableLoading"
                ref="table" size="medium" border
                :data="ruleForm.inspectDrivers">
        <el-table-column label="序号" type="index" width="80" align="center"/>
        <el-table-column min-width="160" show-overflow-tooltip prop="formatInspectTime" label="期望巡检时间" align="center"/>
        <el-table-column min-width="80" show-overflow-tooltip prop="driverName" label="河流名称" align="center"/>
        <el-table-column min-width="80" show-overflow-tooltip prop="driverAreaText" label="区划" align="center"/>
        <el-table-column min-width="80" show-overflow-tooltip prop="driverLength" label="长度" align="center"/>
        <el-table-column min-width="80" show-overflow-tooltip prop="driverStart" label="起点" align="center"/>
        <el-table-column min-width="80" show-overflow-tooltip prop="driverEnd" label="终点" align="center"/>
        <el-table-column min-width="180" show-overflow-tooltip prop="driverFile" label="航线文件" align="center">
          <template slot-scope="{row,$index}">
            <el-button @click="uploadFileTable($index)" v-if="!row.driverFilename" size="small" type="primary"
                       icon="el-icon-plus" circle></el-button>
            <div v-else>
              <el-button style="margin-right: 10px" circle @click="driverFileClose($index)" size="small" icon="el-icon-delete" type="danger"></el-button><span>{{row.driverFilename}}</span>
            </div>
<!--            <el-tag-->
<!--              style="width: 160px"-->
<!--              v-else-->
<!--              closable-->
<!--              @close="driverFileClose($index)"-->
<!--              effect="dark">-->
<!--              {{row.driverFilename}}-->
<!--            </el-tag>-->
          </template>
        </el-table-column>
      </el-table>
      <el-tag class="bt-tag" style="margin-bottom: 15px" effect="dark">任务分配</el-tag>
      <el-form-item label="执行时间" prop="executionTime" :rules="{
                    required: true, message: '执行时间不能为空', trigger: 'change'
                  }">
        <el-date-picker
          placeholder="选择的时间"
          clearable
          value-format="yyyy-MM-dd"
          v-model="ruleForm.executionTime"
          type="date">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="无人机设备" prop="equipmentList" :rules="{
                    required: true, message: '无人机设备不能为空', trigger: 'change'
                  }">
        <el-button @click="addSelectTable(1)" icon="el-icon-plus" type="primary" size="small">增加</el-button>
        <el-button @click="delSelectTable(1)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
        <el-table border stripe @selection-change="handleEquipmentChange" style="margin-top: 10px" size="medium"
                  :data="ruleForm.equipmentList">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column min-width="120" show-overflow-tooltip prop="typeName" label="无人机类型" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="equipmentSn" label="设备编号" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="name" label="设备名称" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="brand" label="设备品牌" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="model" label="设备型号" align="center"/>
        </el-table>
      </el-form-item>
      <el-form-item label="挂载设备">
        <el-button @click="addSelectTable(2)" icon="el-icon-plus" type="primary" size="small">增加</el-button>
        <el-button @click="delSelectTable(2)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
        <el-table border stripe @selection-change="handleMountequipmentChange" style="margin-top: 10px" size="medium"
                  :data="ruleForm.mountequipmentList">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column min-width="120" show-overflow-tooltip prop="typeName" label="无人机类型" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="equipmentSn" label="设备编号" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="name" label="设备名称" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="brand" label="设备品牌" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="model" label="设备型号" align="center"/>
        </el-table>
      </el-form-item>
      <el-form-item label="飞手" prop="inspectHandList" :rules="{
                    required: true, message: '飞手不能为空', trigger: 'change'
                  }">
        <el-button @click="addSelectTable(3)" icon="el-icon-plus" type="primary" size="small">增加</el-button>
        <el-button @click="delSelectTable(3)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
        <el-table border stripe @selection-change="handleInspectHandChange" style="margin-top: 10px;width: 260px"
                  size="medium"
                  :data="ruleForm.inspectHandList">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column show-overflow-tooltip prop="realname" label="姓名" align="center"/>
        </el-table>
      </el-form-item>
      <div style="width: 100%;text-align: center;margin-top: 20px">
        <el-button icon="el-icon-document-add" type="primary" size="medium" :loading="submitLoading"
                   @click="submitForm('dialogForm')">确定
        </el-button>
        <el-button icon="el-icon-back" size="medium" class="back"
                   @click="$emit('close')">返回
        </el-button>
      </div>
    </el-form>
    <input id="upload" type="file" name="file" @change="uploadClick" style="display: none;">
    <allotTasksAdd :equipmentTypeList="equipmentTypeList" :dataTime="dataTime" @submit="addSubmit" @close="addClose" :addType="addType"
                   :visible="addVisible"></allotTasksAdd>
  </el-drawer>
</template>

<script>
  import $ from 'jquery'
  import userApi from '@/api/user/user'
  import inspectApi from '@/api/business/inspect'
  import allotTasksAdd from './allotTasksAdd'

  export default {
    name: "allotTasks",
    data() {
      return {
        submitLoading: false,
        addVisible: false,
        addType: -1,
        dataTime: -1,
        mainTableLoading: false,
        drawerWidth: (document.body.clientWidth - 190) + 'px',
        direction: 'rtl',
        mountequipmentSelect: [],
        equipmentSelect: [],
        inspectHandSelect: [],
        ruleForm: {
          inspectDrivers: [],
          executionTime: ''
        },
        fileIndex: ''
      }
    },
    components: {allotTasksAdd},
    computed: {
      getTypeText() {
        return this.$root.$options.filters.unique(this.inspectDrivers, 'type')
      }
    },
    mounted() {
      let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
      ruleForm.inspectDrivers = JSON.parse(JSON.stringify(this.inspectDrivers))
      this.ruleForm = Object.assign({}, ruleForm)
    },
    props: {
      visible: {
        type: Boolean,
        default() {
          return false;
        }
      },
      inspectDrivers: {
        type: Array,
        default() {
          return []
        }
      },
      equipmentTypeList:{
        type: Object,
        default() {
          return {}
        }
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            if (ruleForm.inspectHandList && ruleForm.inspectHandList.length > 0) {
              let list = []
              ruleForm.inspectHandList.map(item => {
                list.push(item.id)
              })
              ruleForm.inspectHand = list.join(',')
            }else{
              ruleForm.inspectHand =''
            }
            delete ruleForm.inspectHandList

            if (ruleForm.equipmentList && ruleForm.equipmentList.length > 0) {
              let list = []
              ruleForm.equipmentList.map(item => {
                list.push(item.id)
              })
              ruleForm.equipmentId = list.join(',')
            }else{
              ruleForm.equipmentId =''
            }
            delete ruleForm.equipmentList
            if (ruleForm.mountequipmentList && ruleForm.mountequipmentList.length > 0) {
              let list = []
              ruleForm.mountequipmentList.map(item => {
                list.push(item.id)
              })
              ruleForm.mountequipmentId = list.join(',')
            }else{
              ruleForm.mountequipmentId =''
            }
            delete ruleForm.mountequipmentList
            ruleForm.executionTime=new Date(ruleForm.executionTime).getTime()
            this.submitLoading = true
            inspectApi.assignTask(ruleForm).then(res => {
              this.$message({
                type: 'success',
                message: '分配任务成功'
              })
              this.submitLoading = false
              this.$emit('okSubmit')
            }).catch(e => {
              this.submitLoading = false
            })
          }
        })
      },
      addSubmit(subList, addType) {
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
        if (addType == 1) {
          subList.map(item => {
            if (ruleForm.equipmentList && ruleForm.equipmentList.length > 0) {
              if (!ruleForm.equipmentList.some(child => child.id == item.id)) {
                ruleForm.equipmentList.push(item)
              }
            } else {
              ruleForm.equipmentList = [item]
            }
          })
          this.$refs.dialogForm.clearValidate('equipmentList')
        } else if (addType == 2) {
          subList.map(item => {
            if (ruleForm.mountequipmentList && ruleForm.mountequipmentList.length > 0) {
              if (!ruleForm.mountequipmentList.some(child => child.id == item.id)) {
                ruleForm.mountequipmentList.push(item)
              }
            } else {
              ruleForm.mountequipmentList = [item]
            }
          })
          this.$refs.dialogForm.clearValidate('mountequipmentList')
        } else if (addType == 3) {
          subList.map(item => {
            if (ruleForm.inspectHandList && ruleForm.inspectHandList.length > 0) {
              if (!ruleForm.inspectHandList.some(child => child.id == item.id)) {
                ruleForm.inspectHandList.push(item)
              }
            } else {
              ruleForm.inspectHandList = [item]
            }
          })
          this.$refs.dialogForm.clearValidate('inspectHandList')
        }
        this.ruleForm = Object.assign({}, ruleForm)
        this.addVisible = false
      },
      handleEquipmentChange(val) {
        this.equipmentSelect = val
      },
      handleMountequipmentChange(val) {
        this.mountequipmentSelect = val
      },
      handleInspectHandChange(val) {
        this.inspectHandSelect = val
      },
      delSelectTable(addType) {
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
        let dataList = []
        let selectList = []
        if (addType == 1) {
          dataList = ruleForm.equipmentList
          selectList = this.equipmentSelect
        } else if (addType == 2) {
          dataList = ruleForm.mountequipmentList
          selectList = this.mountequipmentSelect
        } else if (addType == 3) {
          dataList = ruleForm.inspectHandList
          selectList = this.inspectHandSelect
        }
        if (selectList.length == dataList.length) {
          if (addType == 1) {
            ruleForm.equipmentList = []
          } else if (addType == 2) {
            ruleForm.mountequipmentList = []
          } else if (addType == 3) {
            ruleForm.inspectHandList = []
          }
        } else {
          if (addType == 1) {
            for (let i = ruleForm.equipmentList.length - 1; i >= 0; i--) {
              if (selectList.some(item => item.id == ruleForm.equipmentList[i].id)) {
                ruleForm.equipmentList.splice(i, 1)
              }
            }
          } else if (addType == 2) {
            for (let i = ruleForm.mountequipmentList.length - 1; i >= 0; i--) {
              if (selectList.some(item => item.id == ruleForm.mountequipmentList[i].id)) {
                ruleForm.mountequipmentList.splice(i, 1)
              }
            }
          } else if (addType == 3) {
            for (let i = ruleForm.inspectHandList.length - 1; i >= 0; i--) {
              if (selectList.some(item => item.id == ruleForm.inspectHandList[i].id)) {
                ruleForm.inspectHandList.splice(i, 1)
              }
            }
          }
        }
        if (addType == 1) {
          this.equipmentSelect = []
        } else if (addType == 2) {
          this.mountequipmentSelect = []
        } else if (addType == 3) {
          this.inspectHandSelect = []
        }
        this.ruleForm = Object.assign({}, ruleForm)
      },
      addSelectTable(addType) {
        this.addType = addType
        this.dataTime = new Date().getTime()
        this.$nextTick(function () {
          this.addVisible = true
        })
      },
      addClose() {
        this.addVisible = false
      },
      uploadClick(event) {
        let file = event.target.files[0]
        // if (this.fileIndex != -1) {
        //   if (!/\.(kml)$/.test(event.target.value)) {
        //     this.$message.error('上传格式不对');
        //     event.target.value = ''
        //     return
        //   }
        let formdata = new window.FormData()
        formdata.append('file', file)
        this.mainTableLoading = true
        userApi.upload(formdata).then((rs) => {
          this.$message({
            type: "success",
            message: "上传成功"
          });
          let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
          ruleForm.inspectDrivers[this.fileIndex].driverFilename = rs.data.fileName
          ruleForm.inspectDrivers[this.fileIndex].driverFile = rs.data.url
          this.ruleForm = Object.assign({}, ruleForm)
          this.mainTableLoading = false
        }, error => {
          this.mainTableLoading = false
        });
        event.target.value = ''
      },
      driverFileClose(index) {
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
        ruleForm.inspectDrivers[index].driverFilename = ''
        ruleForm.inspectDrivers[index].driverFile = ''
        this.ruleForm = Object.assign({}, ruleForm)
      },
      uploadFileTable(index) {
        this.fileIndex = index
        $('#upload').click()
      },
      handleClose(hide) {
        if (hide) {
          hide()
        }
        this.$emit('close')
      }
    }
  }
</script>

<style lang="less">
  .allotTasks {
    .bt-tag {
      height: 28px;
      padding: 0 10px;
      text-align: center;
      line-height: 28px;
      width: 120px;
      font-size: 14px;
      border-radius: 0px;
    }
  }
</style>
