<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item  prop="proName">
          <el-input
            v-model="queryParams.proName"
            placeholder="工程名称"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>

        <el-form-item  prop="powerName">
          <el-input
            v-model="queryParams.powerName"
            placeholder="杆塔编号"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item  prop="teamName">
          <el-input
            v-model="queryParams.teamName"
            placeholder="领用班组"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item  prop="devName">
          <el-input
            v-model="queryParams.devName"
            placeholder="设备名称"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>
       
        <el-form-item  prop="devCode">
          <el-input
            v-model="queryParams.devCode"
            placeholder="设备编码"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item prop="devType">
          <el-select v-model="queryParams.devType" placeholder="设备类型" clearable style="width: 100%;">
            <el-option
              v-for="dict in dict.type.sys_device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="lyTime">
          <el-date-picker
            v-model="queryParams.lyTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            placeholder="领用时间"
            type="date"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="ghTime">
          <el-date-picker
            v-model="queryParams.ghTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            placeholder="归还时间"
            type="date"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['basic:equipmentReq:addData']"
          >设备领用</el-button>
        </el-col>
        
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="80" type="index">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
        <el-table-column label="工程名称" align="center" prop="proName" sortable/>
        <el-table-column label="项目部名称" align="center" prop="departName" sortable/>
        <el-table-column label="作业杆塔名称" align="center" prop="powerName" sortable/>
        <el-table-column label="领用班组" align="center" prop="teamName" sortable/>
        <el-table-column label="领用设备类型" align="center" prop="deviceTypeName" sortable/>
        <el-table-column label="设备名称" align="center" prop="devName" sortable/>
        <el-table-column label="领用设备编码" align="center" prop="devCode" sortable/>
        <!-- <el-table-column label="班组负责人" align="center" prop="bindNum"></el-table-column> -->
        <el-table-column label="领用时间" align="center" prop="lyTime" sortable/>
        <el-table-column label="归还时间" align="center" prop="ghTime" sortable>
          <template slot-scope="scope">
            <span v-if="!scope.row.ghTime" style="font-weight: bold;color: green;">在用</span>
            <span v-else>{{ scope.row.ghTime }}</span>
          </template>
        </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)" 
            >编辑</el-button> -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete" 
              v-hasPermi="['basic:equipmentReq:returnDevice']"
              v-if="!scope.row.ghTime"
              @click="returnDevice(scope.row)" 
            >归还</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      
      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="领用班组" prop="teamId">
                <el-select v-model="form.teamId" placeholder="请选择领用班组" clearable style="width: 100%;" @change="changeTeam">
                    <el-option
                    v-for="dict in teamList"
                    :key="dict.teamId"
                    :label="dict.teamName"
                    :value="dict.teamId"
                    />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="班组长" prop="teamUserName">
                    <el-input v-model="form.teamUserName" placeholder="班组长" disabled/>
                </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
                <el-form-item label="所属工程" prop="proName">
                    <el-input v-model="form.proName" placeholder="所属工程" disabled/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="作业杆塔编号" prop="powerId">
                    <el-select v-model="form.powerId" placeholder="请选择作业杆塔编号" clearable style="width: 100%;">
                        <el-option
                        v-for="dict in GtList"
                        :key="dict.id+''"
                        :label="dict.name"
                        :value="dict.id+''"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
          </el-row> 
          <!-- 选择设备 -->
          <el-row :gutter="24" style="border: 1px dashed #000;width: 95%;margin: 20px auto;">
            <div style="margin: 20px;color: #0068E3;" @click="addDevice">添加</div>
            <div v-for="(item,index) in form.list" :key="index">
              <el-col :span="11"> 
                <el-form-item label="领用设备类型" :prop="`list[${index}].devType`" :rules="[{ required: true, message: '请选择', trigger: 'change' }]" >
                  <el-select v-model="item.devType" placeholder="请选择领用设备类型" clearable style="width: 100%;" @change="changeType($event,item)">
                    <el-option
                      v-for="dict in dict.type.sys_device_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="领用设备编码" :prop="`list[${index}].devCode`" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
                    <el-select v-model="item.devCode" placeholder="请选择领用设备编码" filterable clearable style="width: 100%;" @change="changeDevice($event,item)" @focus="focusDevice(item.devType)">
                        <el-option
                        v-for="dict in deviceList"
                        :key="dict.devCode+''"
                        :label="dict.devName"
                        :value="dict.devCode+''"
                        :disabled="dict.disabled"
                        />
                    </el-select>
                </el-form-item>
              </el-col>  
              <el-col :span="2">
                <div @click="removeSetting(index)" v-show="index!=0"><i class="el-icon-delete" style="font-size: 18px;color: red;"></i></div>
              </el-col>              
            </div>
 
          </el-row>

          <el-col :span="24">
              <el-form-item label="备 注" prop="remarks">
                  <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
              </el-form-item>
          </el-col>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

  

      

    </div>
  </template>
  
  <script>
  import { listSideband, addSideband, editSideband, getSidebandInfo, delSideband,listDevice,delDevice,listDeviceNoBind,bindDevice, exportPerson} from "@/api/construction/sideband";
  import { equipmentReqList,addEquipmentData,getUseDevices,returnDevice} from "@/api/construction/deviceReceive";
  import { getTeamLists,getPowerLists,getDeviceLists } from "@/api/select";
  import { downloadFile } from '@/utils/download'
  import { getToken } from '@/utils/auth'
  import uploadFile from '../../components/uploadFile.vue'
  export default {
    name: "Post",
    dicts: ['sys_device_type'],
    components: {
			uploadFile
		},
    data() {
      return {
        // 遮罩层
        loading: true,
 
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //绑定设备总条数
        totalTwo:0,
        //未绑定设备总条数
        totalThree:0,
        // 人员表格数据
        tableList: [],  
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //班组下拉数据
        teamList: [],
        //设备下拉数据
        deviceList: [],
        //施工杆塔
        GtList:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          // sidebandName: undefined,
          // sidebandCode: undefined,
          // projectName: undefined,
          // gtCode: undefined,
          // bindTime: undefined,
        },
        stateList:['在用','未用'], 
        // 表单参数
        form: {
          list:[]
        },
        // 表单校验
        rules: {
          teamId: [
            { required: true, message: "请选择领用班组", trigger: "blur" }
          ],
          powerId: [
            { required: true, message: "请选择作业杆塔编号", trigger: "blur" }
          ],
        }
      };
    },
    computed: {
 
    },
    created() {
      this.getTeamLists(); 
      this.getList();
    },
    mounted(){
      console.log(this.dict.type.sys_device_type)
    },
    methods: {

 
        /** 查询列表 */
        getList() {
            this.loading = true;
            equipmentReqList(this.queryParams).then(response => {
              this.tableList = response.rows;
              this.total = response.total;
              this.loading = false;
            });
        },
 
        // 取消按钮
        cancel() {
            this.open = false;
            this.fileList=[];
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
              list:[{devId:"",devName:"",devCode:"",devType:""}]
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
 
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.deviceId)
            this.single = selection.length!=1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "设备领用";
        },
        //获取班组
        getTeamLists(){
          getTeamLists().then(response => {
               this.teamList = response.data;
            });
        },
        changeTeam(val){
          let obj = this.teamList.filter(item => {
              return item.teamId == val
          })
          this.form.proId = obj[0].proId;
          this.form.teamUserName = obj[0].teamLeader;
          this.form.proName = obj[0].proName; 
          this.getPowerLists(obj[0].proId)

        },
        //获取杆塔
        getPowerLists(proId){
          getPowerLists({proId:proId}).then(response => {
               this.GtList = response.data;
            });
        },
        //添加设备
        addDevice() {
          this.form.list.push({
            'devId': '',
            'devName': '',
            'devCode': '',
            'devType': '',
          })
        },
        //类型改变
        changeType(val,listItem){
          this.form.list.forEach(item=>{
            if(item.devCode==listItem.devCode){
              item.devCode=''
            }
          })
          
        },
        //聚焦设备列表select时根据类型更新下拉数据
        focusDevice(type){
          this.getDeviceList(type)
        },
        changeDevice(val,listItem){
          for(let i=0;i<this.deviceList.length;i++){//选择设备将form.list中devName和devId赋值
            this.form.list.forEach(item=>{
              if(item.devCode==this.deviceList[i].devCode){
                item.devName=this.deviceList[i].devName;
                item.devId=this.deviceList[i].devId;
              }                  
            })
          }
        },
        getDeviceList(type){
          this.deviceList=[]
          getUseDevices({devType:type}).then(response => {
              this.deviceList = response.data;
              for(let i=0;i<this.deviceList.length;i++){//渲染设备下拉数据时将已选择的设备禁用
                this.form.list.forEach(item=>{
                  if(item.devCode==this.deviceList[i].devCode){
                    this.deviceList[i].disabled=true
                  }                  
                })
              }
          });
        },
        //删除设备
        removeSetting(index) {
          if (index !== 0) {
            this.form.list.splice(index, 1)
          }
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const sidebandId = row.sidebandId
            this.fileList=[];
            getSidebandInfo(sidebandId).then(response => {
              this.form = response.data;
              console.log(response.data.gtCode)
              this.$set(this.form,'projectName',response.data.projectName+'')
              this.$set(this.form,'gtCode',response.data.gtCode+'')
              setTimeout(()=>{
                this.open = true;
                this.title = "设备领用";
              },100)
             
            });
        }, 
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
            if (valid) {//
              console.log(this.form)
                  addEquipmentData(this.form).then(response => {
                    console.log(response)
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
            }
            });
        },

        /** 删除按钮操作 */
        returnDevice(row) {
            console.log(row)
            const param = {
              "id": row.id,
              "devId": row.devId,
              "devType": row.devType,
              "devCode": row.devCode
            }
            this.$modal.confirm('是否确认归还名称为"' + row.devName + '"的数据项？').then(function() {
              return returnDevice(param);
            }).then(() => {
              this.getList();
              this.$modal.msgSuccess("归还成功");
            }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
          exportPerson(this.queryParams).then(res => {
            downloadFile({ fileName: `人员_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
          })
        },

        /** 导入按钮操作 */
        handleImport() {
          this.upload.title = "导入";
          this.upload.open = true;
        },
 
 
  
    }
  };
  </script>

  <style lang="scss" scoped>
  ::v-deep.el-table .fixed-width .el-button--mini {
      width: 60px !important;
      margin-bottom: 10px;
  }
  //隐藏图片上传框的css
  ::v-deep.disabled {
      .el-upload--picture-card {
          display: none;
      }
  }
  </style>