<template>
  <div class="inspect-container">
    <el-form ref="ruleForm" :model="ruleForm"  label-width="120px">
      <el-form-item label="任务类型" prop="type" :rules="{
                    required: true, message: '任务类型不能为空', trigger: 'change'
                  }">
        <el-radio-group v-model="ruleForm.type" size="medium">
          <el-radio label="1" border>可见光巡检</el-radio>
          <el-radio label="2" border>多光谱巡检</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="期望巡检时间" prop="inspectTime" :rules="{
                    required: true, message: '期望巡检时间不能为空', trigger: 'change'
                  }">
        <el-date-picker
          placeholder="选择的时间"
          clearable
          size="medium"
          value-format="yyyy-MM-dd"
          v-model="ruleForm.inspectTime"
          type="date">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="河道信息">
        <el-button @click="addData" icon="el-icon-plus" type="primary" size="small">增加</el-button>
        <el-button @click="delData" size="small" type="danger" icon="el-icon-delete">删除</el-button>
        <el-table v-loading="mainTableLoading" stripe @selection-change="handleSelectionChange" style="margin-top: 10px"
                  ref="table" size="medium"
                  :data="dataList">
          <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="60" show-overflow-tooltip prop="name" label="河流名称" align="center"/>
          <el-table-column min-width="60" show-overflow-tooltip prop="driverAreaName" label="区划" align="center"/>
          <el-table-column min-width="60" show-overflow-tooltip prop="startPoint" label="起点" align="center"/>
          <el-table-column min-width="60" show-overflow-tooltip prop="endPoint" label="终点" align="center"/>
          <el-table-column min-width="60" show-overflow-tooltip prop="length" label="长度" align="center"/>
          <el-table-column min-width="60" 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>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="总长度">
        <el-input style="width: 200px" :disabled="true" clearable v-model="ruleForm.inspectLength" size="medium"/>
        公里
      </el-form-item>
      <el-form-item label="附件">
        <div v-if="!ruleForm.attachment">
          <el-button :loading="fjUploadLoading" @click="uploadFileTable(-1)" size="small" type="primary"
                     icon="el-icon-upload2">上传
          </el-button>
          <span style="margin-left: 5px;color: #999999">支持扩展名：.rar .zip .doc .docx .pdf .jpg</span>
        </div>
        <el-tag
          v-else
          closable
          @close="attachmentClose"
          effect="dark">
          {{ruleForm.attachmentName}}
        </el-tag>
      </el-form-item>
      <el-form-item label="备注">
        <el-input maxlength="200"
                  show-word-limit clearable v-model="ruleForm.note" type="textarea" rows="5" size="medium"
                  placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <div v-if="isAdmin||btnRule.some(btn=>btn=='add')" style="text-align: center">
      <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="medium"
                 @click="submitForm('ruleForm')">立即提交
      </el-button>
      <el-button icon="el-icon-refresh-right" @click="ruleFormReset" size="medium">重置
      </el-button>
    </div>
    <el-drawer
      title="添加河道信息"
      :visible.sync="addDialogVisible"
      :direction="direction"
      :size="drawerWidth"
      :before-close="handleClose">
      <el-form label-position='left' :inline="true" v-if="addDialogVisible" ref="dialogForm" :model="dialogForm"
               size="small"
               label-width="70px"
               class="form">
        <el-form-item label="区划" label-width="40px">
          <driverAreaSelect v-model="dialogForm.driverArea"></driverAreaSelect>
        </el-form-item>
        <el-form-item label="河湖名称">
          <el-input
            clearablename
            v-model="dialogForm.name"
            placeholder="请输入河湖名称"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="tableLoading"
            @click="searchTable"
            icon="el-icon-search"
            type="primary"
          >搜索
          </el-button>
          <el-button
            @click="initSearchParam(),searchTable()"
            icon="el-icon-refresh-right"
            type="primary"
            style="background-color: #fff; border: 1px solid #ccc ; color: #666"
          >重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="dialogTable"
        v-if="addDialogVisible"
        row-key="id"
        :max-height="tableHeight"
        v-loading="tableLoading"
        size="medium"
        stripe
        :data="driverList"
        @selection-change="handleMultipleChange"
        border
      >
        <el-table-column
          :reserve-selection="true"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column :index="indexMethod" label="序号" type="index" width="80" align="center"/>
        <el-table-column align="center" prop="name" label="河湖名称"/>
        <el-table-column align="center" prop="driverAreaName" label="区划"/>
        <el-table-column align="center" prop="startPoint" label="起点"/>
        <el-table-column prop="endPoint" align="center" label="终点"/>
        <el-table-column prop="length" align="center" label="长度"/>
      </el-table>
      <div class="foot-page">
        <el-pagination
          @current-change="currentChange"
          background
          :current-page.sync="dialogForm.page"
          :page-size="dialogForm.pageSize"
          layout="total,prev, pager, next, jumper"
          :total="dialogForm.total"
        ></el-pagination>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 20px">
        <el-button icon="el-icon-document-add" type="primary" size="medium"
                   @click="dialogSubmitForm('dialogForm')">确定
        </el-button>
        <el-button icon="el-icon-back" size="medium" class="back"
                   @click="dialogback">返回
        </el-button>
      </div>
    </el-drawer>
    <input id="upload" type="file" name="file" @change="uploadClick" style="display: none;">
  </div>

</template>

<script>
  import driverApi from '@/api/basicData/driver'
  import inspectApi from '@/api/business/inspect'
  import driverAreaSelect from '@/components/driverAreaSelect'
  import userApi from '@/api/user/user'
  import $ from 'jquery'
  import {mapGetters} from "vuex";

  export default {
    name: "inspect",
    data() {
      return {
        fjUploadLoading: false,
        mainTableLoading: false,
        tableLoading: false,
        drawerWidth: (document.body.clientWidth - 190) + 'px',
        direction: 'rtl',
        tableHeight: document.body.clientHeight - 250,
        ruleForm: {
          type: '1',
          inspectTime: '',
          inspectLength: 0,
          attachment: '',
          note: '',
        },
        dialogForm: {
          name: '',
          driverArea: '',
          page: 1,
          pageSize: parseInt((document.body.clientHeight - 250 - 43) / 43),
          total: 0
        },
        selectList: [],
        multipleSelection: [],
        dataList: [],
        driverList: [],
        addBtnLoading: false,
        addDialogVisible: false,
        fileIndex: ''
      }
    },
    created() {
    },
    mounted() {
    },
    components: {driverAreaSelect},
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    methods: {
      handleMultipleChange(val) {
        this.multipleSelection = val;
      },
      uploadFileTable(index) {
        this.fileIndex = index
        $('#upload').click()
      },
      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
        //   }
        // } else {
        //   if (!/\.(rar|zip|doc|docx|pdf|jpg)$/.test(event.target.value)) {
        //     this.$message.error('上传格式不对');
        //     event.target.value = ''
        //     return
        //   }
        //   if (file.size > (1024 * 1024 * 10)) {
        //     this.$message.error('上传格式不能超过10M');
        //     event.target.value = ''
        //     return
        //   }
        // }
        let formdata = new window.FormData()
        formdata.append('file', file)
        if (this.fileIndex != -1) {
          this.mainTableLoading = true
        }else{
          this.fjUploadLoading=true
        }
        userApi.upload(formdata).then((rs) => {
          this.$message({
            type: "success",
            message: "上传成功"
          });
          if (this.fileIndex != -1) {
            let dataList = JSON.parse(JSON.stringify(this.dataList))
            dataList[this.fileIndex].driverFilename = rs.data.fileName
            dataList[this.fileIndex].driverFile = rs.data.url
            this.dataList = Object.assign([], dataList)
          } else {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            ruleForm.attachmentName = rs.data.fileName
            ruleForm.attachment = rs.data.url
            this.ruleForm = Object.assign({}, ruleForm)
          }
          if (this.fileIndex != -1) {
            this.mainTableLoading = false
          }else{
            this.fjUploadLoading=false
          }
        }, error => {
          if (this.fileIndex != -1) {
            this.mainTableLoading = false
          }else{
            this.fjUploadLoading=false
          }
        });
        event.target.value = ''
      },
      driverFileClose(index){
        let dataList = JSON.parse(JSON.stringify(this.dataList))
        dataList[index].driverFilename =''
        dataList[index].driverFile = ''
        this.dataList = Object.assign([], dataList)
      },

      attachmentClose(){
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
        ruleForm.attachmentName = ''
        ruleForm.attachment = ''
        this.ruleForm = Object.assign({}, ruleForm)
      },
      indexMethod(index) {
        return (index + 1) + ((this.dialogForm.page - 1) * this.dialogForm.pageSize);
      },
      initSearchParam() {
        this.dialogForm = {
          name: '',
          driverArea: '',
          page: 1,
          pageSize: parseInt((document.body.clientHeight - 250 - 43) / 43),
          total: 0
        }
      },
      currentChange(page) {
        this.dialogForm.page = page;
        this.search();
      },
      searchTable(){
        this.dialogForm.page = 1;
        this.multipleSelection=[]
        this.$refs.dialogTable.clearSelection()
        this.search();
      },
      search() {
        let dialogForm = JSON.parse(JSON.stringify(this.dialogForm))
        this.tableLoading = true
        driverApi.getDriverList(dialogForm).then(res => {
          const {records, total} = res.data
          this.driverList = records ? records : []
          this.dialogForm.total = total ? total : 0
          this.tableLoading = false
        }).catch(e => {
          this.driverList = []
          this.dialogForm.total = 0
          this.tableLoading = false
        })
      },
      handleClose(done) {
        if (done) {
          done();
        }
      },
      dialogback() {
        this.addDialogVisible = false
      },
      initRuleForm() {
        this.ruleForm = {
          type: '1',
          inspectTime: '',
          inspectLength: 0,
          attachment: '',
          note: '',
        }
      },
      ruleFormReset() {
        this.initRuleForm()
        this.$refs['ruleForm'].resetFields()
        this.selectList = []
        this.dataList = []
      },
      delData() {
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
        if (this.selectList.length == this.dataList.length) {
          this.dataList = []
          ruleForm.inspectLength = 0
        } else {
          let dataList = JSON.parse(JSON.stringify(this.dataList))
          for (let i = dataList.length - 1; i >= 0; i--) {
            if (this.selectList.some(item => item.driverId == dataList[i].driverId)) {
              if (dataList[i].length) {
                ruleForm.inspectLength = ruleForm.inspectLength - parseFloat(dataList[i].length)
                ruleForm.inspectLength = parseFloat(Number(ruleForm.inspectLength).toFixed(4))
              }
              dataList.splice(i, 1)
            }
          }
          this.dataList = Object.assign([], dataList)
        }
        this.ruleForm = Object.assign({}, ruleForm)
        this.selectList = []
      },
      handleSelectionChange(val) {
        this.selectList = val
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            if (this.dataList.length > 0) {
              let inspectDriverList = []
              this.dataList.map(item => {
                inspectDriverList.push({
                  driverId: item.driverId,
                  driverFilename: item.driverFilename,
                  driverFile: item.driverFile
                })
              })
              ruleForm.inspectDriverList = inspectDriverList
            } else {
              ruleForm.inspectDriverList = []
            }
            this.addBtnLoading = true
            inspectApi.addTask(ruleForm).then(res => {
              this.addBtnLoading = false
              this.ruleFormReset()
              this.$message({
                type: 'success',
                message: '任务发布成功！'
              })
            }).catch(e => {
              this.addBtnLoading = false
            })
          }
        })
      },
      dialogSubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let dataList = JSON.parse(JSON.stringify(this.dataList))
            this.multipleSelection.map(item => {
              if (!dataList.some(child => child.driverId == item.driverId)) {
                dataList.push(item)
              }
            })
            this.dataList = Object.assign([], dataList)
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            this.dataList.map(item=>{
              ruleForm.inspectLength = ruleForm.inspectLength + parseFloat(item.length)
            })
            ruleForm.inspectLength = parseFloat(Number(ruleForm.inspectLength).toFixed(4))
            this.ruleForm = Object.assign({}, ruleForm)
            this.addDialogVisible = false
          }
        })
      },
      addData() {
        this.initSearchParam()
        this.driverList = []
        this.multipleSelection = []
        this.$nextTick(function () {
          this.addDialogVisible = true
          this.search()
        })
      },
    }
  }
</script>

<style lang="less">
  .inspect-container {
    height:fit-content;
    background-color: #fff;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);
    padding: 20px 100px;

    .el-input.is-disabled .el-input__inner {
      background-color: #fff;
      color: #333333;
    }

    .el-button + .el-button {
      margin-left: 10px !important;
    }
  }
</style>
