<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="sidebandName">
          <el-input
            v-model="queryParams.sidebandName"
            placeholder="边带名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item  prop="sidebandCode">
          <el-input
            v-model="queryParams.sidebandCode"
            placeholder="边带编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item  prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="工程名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item  prop="gtCode">
          <el-input
            v-model="queryParams.gtCode"
            placeholder="杆塔编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item prop="bindTime">
        <el-date-picker
          v-model="queryParams.bindTime"
          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:sideband:add']"
          >新增边带</el-button>
        </el-col>
        
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="postList" >
        <el-table-column label="边带id" align="center" prop="sidebandId" v-if="false" />
        <el-table-column label="边带名称" align="center" prop="sidebandName" />
        <el-table-column label="边带编码" align="center" prop="sidebandCode" />
        <el-table-column label="所属工程" align="center" prop="projectName" />
        <el-table-column label="杆塔编号" align="center" prop="gtCode" />
        <el-table-column label="绑定时间" align="center" prop="bindTime" />
        <el-table-column label="绑定设备" align="center" prop="bindNum">
          <template slot-scope="scope">
            <div @click="openGt(scope.row)" style="color: #02a7f0; cursor: pointer">
                {{ scope.row.bindNum}}
            </div>
        </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)"
              v-hasPermi="['basic:person:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basic:person:del']"
            >删除</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="showGt" width="1000px" height="1000px" append-to-body>
          <el-form :model="queryKeyword" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item  prop="keyword">
          <el-input
            v-model="queryKeyword.keyword"
            placeholder="请输入关键词"
            clearable
            @keyup.enter.native="handleQueryTemp"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryTemp">查询</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="handleAddDevice"
            v-hasPermi="['basic:sideband:add']"
          >绑定设备</el-button>
        </el-col>
        
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getListTemp"></right-toolbar> -->
      </el-row>

      <el-table v-loading="loadingTwo" :data="bindList" width="600px" height = "600px" >
        <el-table-column label="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceTypeName" >
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" />
        <el-table-column label="设备状态" align="center" prop="deviceStatus" >
        <template slot-scope="scope">
                <div v-if="scope.row.deviceStatus==0" style="color: green;">{{ stateList[Number(scope.row.deviceStatus)] }}</div>
                <div v-if="scope.row.deviceStatus==1" style="color: red;">{{ stateList[Number(scope.row.deviceStatus)] }}</div>
            </template>
          </el-table-column>
        <el-table-column label="领用人" align="center" prop="lyName" />
        <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="handleDelDevice(scope.row)"
              v-hasPermi="['basic:sideband:edit']"
            >解除绑定</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryKeyword.pageNum"
        :limit.sync="queryKeyword.pageSize"
        @pagination="getListTemp"
      />

      </el-dialog>

      <!-- 选择设备弹窗 -->
      <el-dialog :title="title" :visible.sync="showDevice" width="1000px" height="1000px" append-to-body>
          <el-form :model="queryKeywordTemp" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item  prop="keyword">
          <el-input
            v-model="queryKeywordTemp.keyword"
            placeholder="请输入关键词"
            clearable
            @keyup.enter.native="handleQueryDevice"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryDevice">查询</el-button>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleBindDevice"
            v-hasPermi="['basic:sideband:add']"
          >绑定</el-button>
        </el-form-item>
        </el-form>
<!-- 
        <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getListDevice"></right-toolbar>
      </el-row> -->

      <el-table v-loading="loadingThree" :data="bindNoList" width="600px" height = "600px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceTypeName" >
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" />
      </el-table>
  
      <pagination
        v-show="totalThree>0"
        :total="totalThree"
        :page.sync="queryKeywordTemp.pageNum"
        :limit.sync="queryKeywordTemp.pageSize"
        @pagination="getListDevice"
      />

      </el-dialog>

      <!-- 添加或修改边带对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="边带名称" prop="sidebandName">
                        <el-input v-model="form.sidebandName" placeholder="请输入边带名称" />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="边带编码" prop="sidebandCode">
                        <el-input v-model="form.sidebandCode" placeholder="请选择边带编码" />
                    </el-form-item>
                </el-col>
          </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
                    <el-form-item label="所属工程" prop="projectName">
                        <el-select v-model="form.projectName" placeholder="请选择所属工程" clearable style="width: 100%;">
                            <el-option
                            v-for="dict in proList"
                            :key="dict.id"
                            :label="dict.name"
                            :value="dict.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="施工杆塔" prop="gtCode">
                        <el-select v-model="form.gtCode" placeholder="请选择施工班组" clearable style="width: 100%;">
                            <el-option
                            v-for="dict in GtList"
                            :key="dict.id+''"
                            :label="dict.powerName"
                            :value="dict.id+''"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
        </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 { getProList } from "@/api/select";
  import { getGtList } 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_normal_disable','sys_device_type','sys_user_sex'],
    components: {
			uploadFile
		},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 遮罩层2
        loadingTwo:true,
        // 遮罩层3
        loadingThree:true,
        // 选中数组
        
        idLists:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //绑定设备总条数
        totalTwo:0,
        //未绑定设备总条数
        totalThree:0,
        // 人员表格数据
        postList: [],
        // 绑定设备表格数据
        bindList: [],
        // 绑定设备表格数据
        bindNoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //所属工程
        proList: [],
        //施工杆塔
        GtList:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sidebandName: undefined,
          sidebandCode: undefined,
          projectName: undefined,
          gtCode: undefined,
          bindTime: undefined,
        },
        queryKeyword:{
          pageNum: 1,
          pageSize: 10,
          sidebandId: undefined,
          keyword: undefined,
        },
        queryKeywordTemp:{
          pageNum: 1,
          pageSize: 10,
          sidebandId: undefined,
          keyword: undefined,
        },
        showGt:false,

        showDevice:false,

        stateList:['在用','未用'],
        accept:'.png, .jpg, .jpeg, .pdf, .doc, .docx',
        highImgList: [],
        electricianImgList: [],
        elseImgList: [],
        // 表单参数
        form: {},
        //图片上传
        fileList: [],
        //图片查看弹窗
        dialogImageUrl: '',
        dialogVisible: false,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/bracelet/person/excelUpload"
        },
        // 表单校验
        rules: {
          sidebandName: [
            { required: true, message: "边带名称不能为空", trigger: "blur" }
          ],
          sidebandCode: [
            { required: true, message: "边带编码不能为空", trigger: "blur" }
          ],
          projectName: [
            { required: true, message: "所属工程不能为空", trigger: "change" }
          ],
          gtCode: [
            { required: false, trigger: "change" }
          ],
          remarks: [
            { required: false, trigger: "change" }
          ]
        }
      };
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.fileList.length > 0
        },
    },
    created() {
      this.getProList();
      this.getGtList();
      this.getList();
    },
    methods: {
       //获取所属工程
        getProList(){
            getProList().then(response => {
               this.proList = response.data;
            });
        },

       //获取施工杆塔
        getGtList(){
            getGtList().then(response => {
               this.GtList = response.data;
               console.log(this.GtList)
            });
        },

        /** 查询边带列表 */
        getList() {
            this.loading = true;
            listSideband(this.queryParams).then(response => {
              this.postList = response.rows;
              this.total = response.total;
              this.loading = false;
            });
        },
        /** 查询杆塔绑定设备列表 */
        getListTemp() {
            this.loadingTwo = true;
            this.queryKeyword.sidebandId = this.sidebandId;
            listDevice(this.queryKeyword).then(response => {
              this.bindList = response.rows;
              this.total = response.total;
              console.log(this.total)
              this.loadingTwo = false;
            });
        },
        //查询未绑定设备列表
        getListDevice() {
            this.loadingThree = true;
            this.queryKeywordTemp.sidebandId = this.sidebandId;
            listDeviceNoBind(this.queryKeywordTemp).then(response => {
              this.bindNoList = response.rows;
              this.totalThree = response.total;
              this.loadingThree = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.fileList=[];
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {};
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 杆塔页面搜索按钮操作 */
       handleQueryTemp() {
            this.queryKeyword.pageNum = 1;
            this.queryKeyword.sidebandId = this.sidebandId;
            this.getListTemp();
        },
        /** 设备页面搜索按钮操作 */
       handleQueryDevice() {
            this.queryKeywordTemp.pageNum = 1;
            this.queryKeywordTemp.sidebandId = this.sidebandId;
            this.getListDevice();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          // forEach.(selection, function(item){
          //   this.idLists.push({id: item.deviceId, type: item.deviceTypeName})
          // })
          console.log(selection)
          selection.map(item => {
            this.idLists.push({id: item.deviceId, type: item.deviceTypeName})
          })
          // forEach(selection, function(item){
          //   this.idLists.push({id: item.deviceId, type: item.deviceTypeName})
          // })
          // this.idLists.push({id: selection.map(item => item.deviceId), type: selection.map(item => item.deviceTypeName)})

            this.single = selection.length!=1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.fileList = []
            this.reset();
            this.open = true;
            this.title = "添加边带";
        },
        //绑定设备
        handleAddDevice() {
            this.showDevice = true;
            this.title = "选择";
            this.getListDevice();
        },

        handleRemove(file, fileList) {
            let sum = 0
            console.log(111111)
            console.log(this.fileList)
            this.fileList.forEach((item, index) => {
                if (item.uid == file.uid) {
                    sum = index
                }
            })
            
            this.fileList.splice(sum, 1)
        },
        //上传组件-图片查看
        picturePreview(file) {
            console.log(file)
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },


        /** 修改按钮操作 */
        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)
             
            });
        },
         /** 解除绑定操作 */
         handleDelDevice(row) {
            console.log(row)
            const param = {
              sidebandId:row.sidebandId,
              deviceId:row.deviceId,
              deviceTypeName:row.deviceTypeName,
            }
            this.$modal.confirm('确定当前设备与该边带设备解除绑定吗？').then(function() {
              return delDevice(param);
            }).then(() => {
              this.getList();
              this.getListTemp();
              this.$modal.msgSuccess("解除绑定成功");
            }).catch(() => {});
        },

        /** 绑定操作 */
         handleBindDevice(row) {
            console.log(row)
            console.log(this.idLists)
            const deviceIds =  this.idLists;
            console.log(deviceIds)
            const param = {
              sidebandId:this.queryKeywordTemp.sidebandId,
              deviceIds:deviceIds,
            }
            console.log(param)
            if(deviceIds.length==0){
              this.$modal.msgWarning("请选择设备");
              return;
            }
            this.$modal.confirm('确定与该边带绑定吗？').then(function() {
              return bindDevice(param);
            }).then(() => {
              this.getList();
              this.getListTemp();
              this.getListDevice();
              this.$modal.msgSuccess("绑定成功");
            }).catch(() => {});
        },

        /** 提交按钮 */
        submitForm() { 
            this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.form.sidebandId != undefined) {
                  console.log(this.form)
                  editSideband(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    // this.fileList=[];
                    this.getList();
                  });
                } else {
                  console.log(this.form)
                  addSideband(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
            }
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            console.log(row)
            const param = {
              sidebandId:row.sidebandId,
              bindNum:row.bindNum,
            }
            if(row.bindNum>0){
              this.$modal.msgWarning("该边带已绑定设备，无法删除");
              return;
            }
            this.$modal.confirm('是否确认删除边带名称为"' + row.sidebandId + '"的数据项？').then(function() {
              return delSideband(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;
        },


        //打开杆塔页面
        openGt(row){
          this.sidebandId = row.sidebandId;
          this.title = "杆塔"
          this.showGt = true;
          this.getListTemp();
        },
        //打开设备页面
        openDevice(row){
          this.sidebandId = row.sidebandId;
          this.title = "选择"
          this.showDevice = true;
          this.getListDevice();
        },
        
        //关闭证书上传
        cancelGt(){
          this.highImgList = []
          this.electricianImgList = []
          this.elseImgList = []
          this.showGt = false;
        },
        //提交证书上传
        submitCertificate(){
          console.log(this.highImgList)
          console.log(this.electricianImgList)
          console.log(this.elseImgList)
          // this.highImgList = []
          // this.electricianImgList = []
          // this.elseImgList = []

          this.showGt = false;
        },
  
    }
  };
  </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>