<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent label-width="100px">
      <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleImpUnitChange"
        >
          <el-option
            v-for="item in impUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目部" prop="departName">
        <el-select
          v-model="queryParams.departName"
          placeholder="请选择项目部"
          clearable
          filterable
          style="width: 240px"
          @change="handleDepartChange"
        >
          <el-option
            v-for="item in departOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="工程" prop="proName">
        <el-select
          v-model="queryParams.proName"
          placeholder="请选择工程"
          clearable
          filterable
          style="width: 240px"
          @change="getTeamListAndSubUnit"
        >
          <el-option
            v-for="item in proOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分包单位" prop="subUnitName">
        <el-select
          v-model="queryParams.subUnitName"
          placeholder="请选择分包单位"
          clearable
          filterable
          style="width: 240px"
          @change="getTeamList"
        >
          <el-option
            v-for="item in subUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班组名称" prop="teamName">
        <el-select
          v-model="queryParams.teamName"
          placeholder="请选择班组"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in teamOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <el-table-column label="分公司" align="center" prop="impUnitName" />
      <el-table-column label="项目部" align="center" prop="departName" />
      <el-table-column label="工程名称" align="center" prop="proName" />
      <el-table-column label="分包单位" align="center" prop="subUnitName" />
      <el-table-column label="班组名称" align="center" prop="teamName" />
      <el-table-column label="班组长" align="center" prop="teamLeaderIdCard"   />
      <el-table-column label="库存" align="center" prop="usNum" >
        <template slot-scope="scope">
          <span
            v-if="scope.row.usNum > 0"
            class="clickText"
            @click="openUserRecords(scope.row)"
          >
            {{ scope.row.usNum }}
          </span>
          <!-- 否则，直接显示数字 -->
          <span v-else>
            {{ scope.row.usNum }}
          </span>
        </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="openUseRecord" width="1200px" append-to-body>
      <el-form :model="dialogUseQuery" ref="dialogUseQuery" size="small" :inline="true" label-width="80px">
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="dialogUseQuery.keyWord"
            placeholder="请输入关键字"
            clearable
            :maxlength="20"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogUseQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" size="mini" @click="handleDialogUserExport">导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-printer" size="mini" @click="handlePrint">打印</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="useRecordList">
        <el-table-column
          label="序号"
          align="center"
          width="80"
          type="index"
          :index="indexContinuation(dialogUseQuery.pageNum, dialogUseQuery.pageSize)"
        ></el-table-column>
        <el-table-column label="班组名称" align="center" prop="teamName" :show-overflow-tooltip="true" />
        <el-table-column label="领料单号" align="center" prop="code" :show-overflow-tooltip="true" />
        <!-- <el-table-column label="领料人" align="center" prop="leasePerson" :show-overflow-tooltip="true" /> -->
        <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
        <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true" />
        <el-table-column label="单位" align="center" prop="unitName" :show-overflow-tooltip="true" />
        <el-table-column label="库存" align="center" prop="usNum" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" v-if="scope.row.manageType==0" style="margin-bottom: 10px" type="primary" @click="handleView(scope.row)">
            查看
          </el-button>
        </template>
      </el-table-column>
      </el-table>

      <pagination
        v-show="dialogUserTotal > 0"
        :total="dialogUserTotal"
        :page.sync="dialogUseQuery.pageNum"
        :limit.sync="dialogUseQuery.pageSize"
        @pagination="getUserRecords"
      />
    </el-dialog>

    <!-- 二级打印页面 -->
      <el-dialog :visible.sync="openPrint" width="1090px" title="打印预览"  append-to-body>
          <div style="height: 500px; overflow-y: scroll; padding: 0 20px" v-loading="openLoading">
              <vue-easy-print tableShow ref="remarksPrintRef" class="print">
                  <table class="print-table" style="margin-top: 20px; width: 100%; border-collapse: collapse" border>
                      <thead>
                          <tr>
                              <th align="center" style="width: 50px;">序号</th>
                              <th align="center" style="width: 170px;">班组名称</th>
                              <th align="center" style="width: 150px;">领料单号</th>
                              <!-- <th align="center" style="width: 80px;">领料人</th> -->
                              <th align="center" style="width: 200px;">机具名称</th>
                              <th align="center">规格型号</th>
                              <th align="center" style="width: 70px;">单位</th>
                              <th align="center" style="width: 120px;">库存</th>
                          </tr>
                      </thead>
                      <tbody>
                          <tr v-for="(item, index) in useRecordListNoPage" :key="index">
                              <td align="center">{{ index + 1 }}</td>
                              <td align="center">{{ item.teamName }}</td>
                              <td align="center">{{ item.code }}</td>
                              <!-- <td align="center">{{ item.leasePerson }}</td> -->
                              <td align="center">{{ item.typeName }}</td>
                              <td align="center">{{ item.typeModelName }}</td>
                              <td align="center">{{ item.unitName }}</td>
                              <td align="center">{{ item.usNum }}</td>
                          </tr>
                      </tbody>
                  </table>
              </vue-easy-print>
          </div>
          <div slot="footer" class="dialog-footer" style="text-align: center">
              <el-button type="primary" @click="print">打 印</el-button>
              <el-button @click="openPrint = false">关 闭</el-button>
          </div>
      </el-dialog>

    <!-- 三级页面 -->
    <el-dialog :title="titleThree" :visible.sync="openUseRecordThree" width="800px" append-to-body>
      <el-form :model="dialogUseQueryThree" ref="dialogUseQueryThree" size="small" :inline="true" label-width="80px">
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="dialogUseQueryThree.keyWord"
            placeholder="请输入关键字"
            clearable
            :maxlength="20"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogUseQueryThree">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" size="mini" @click="handleResetThree">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="useRecordListThree">
        <el-table-column
          label="序号"
          align="center"
          width="80px"
          type="index"
          :index="indexContinuation(dialogUseQueryThree.pageNum, dialogUseQueryThree.pageSize)"
        ></el-table-column>
        <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
        <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true" />
        <el-table-column label="设备编号" align="center" prop="maCode" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="dialogUserThreeTotal > 0"
        :total="dialogUserThreeTotal"
        :page.sync="dialogUseQueryThree.pageNum"
        :limit.sync="dialogUseQueryThree.pageSize"
        @pagination="getTeamNumThird"
      />
    </el-dialog>
  </div>

  
</template>

<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import QRCodeView from '@/components/QRCodeView'
import { getTeamNumListApi,getTeamNumSecondListApi, getTeamNumThirdApi,getImpUnitListApi, getDepartListByImpUnitApi, getProListByDepartApi, getTeamList, getSubUnitList,getTeamNumSecondListNoPageApi } from '@/api/materialsStation'
import vueEasyPrint from 'vue-easy-print'
import printJS from 'print-js'
export default {
  name: 'TeamStorage',
  components: { TreeSelect, QRCodeView,vueEasyPrint },
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        status: '', // 规格型号
        impUnitName: '', // 分公司
        departName: '', // 项目部
        proName: '', // 工程
        subUnitName: '', // 分包单位
        teamName: '', // 班组名称
      },
      total: 0, // 总条数
      // 表格数据
      tableList: [],
      //在用弹窗
      openUseRecord: false,
      dialogUseQuery: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined
      },
      useRecordList: [],
      useRecordListNoPage: [],
      dialogUserTotal: 0,
      loading: false,
      title: '库存查看',
      openUseRecordThree: false,
      dialogUseQueryThree: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined
      },
      useRecordListThree: [],
      dialogUserThreeTotal: 0,
      titleThree: '查看',
      impUnitOptions: [],   // 分公司下拉
      departOptions: [],    // 项目部下拉
      proOptions: [],       // 工程下拉
      subUnitOptions: [],   // 分包单位下拉
      teamOptions: [],      // 班组下拉
      openPrint: false,     // 打印页面开关
      openLoading: false,   // 打印页面加载
    }
  },
  created() {
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.handleDepartChange()
    this.getTeamList()
    this.getSubUnitList()
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.queryParams.keyWord = ''
      this.queryParams.status = ''
      this.getImpUnitOptions()
      this.handleImpUnitChange()
      this.handleDepartChange()
      this.getTeamList()
      this.getSubUnitList()
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      const loading = this.$loading({ text: '加载中...' })
      try {
        const params = { ...this.queryParams }
        const res = await getTeamNumListApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows
        this.total = res.data.total
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
        loading.close()
      }
    },

    /** 获取分公司下拉 */
    async getImpUnitOptions() {
      try {
        const res = await getImpUnitListApi() // 调后台接口
        this.impUnitOptions = res.data.map(item => ({
          label: item.impUnitName,   // 这里根据实际字段替换
          value: item.impUnitName
        }))
      } catch (e) {
        console.error('获取分公司下拉失败:', e)
      }
    },
    /** 分公司选择变化，加载项目部 */
    async handleImpUnitChange() {
      this.queryParams.departName = null // 清空项目部已选
      this.departOptions = []            // 清空原有下拉

      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getDepartListByImpUnitApi(params)
        this.departOptions = res.data.map(item => ({
          label: item.departName,   // 项目部名称字段
          value: item.departName
        }))
      } catch (e) {
        console.error('获取项目部下拉失败:', e)
      }
    },
    /** 项目部选择变化，加载工程 */
    async handleDepartChange() {
      this.queryParams.proName = null // 清空工程已选
      this.proOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getProListByDepartApi(params)
        this.proOptions = res.data.map(item => ({
          label: item.proName,   // 工程名称字段
          value: item.proName
        }))
      } catch (e) {
        console.error('获取工程下拉失败:', e)
      }
    },
    /** 项目部选择变化，加载工程 */
    async getTeamListAndSubUnit() {
      this.queryParams.teamName = null // 清空工程已选
      this.teamOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getTeamList(params)
        this.teamOptions = res.data.map(item => ({
          label: item.teamName,   // 工程名称字段
          value: item.teamName
        }))
      } catch (e) {
        console.error('获取班组下拉失败:', e)
      }

      this.queryParams.subUnitName = null // 清空工程已选
      this.subUnitOptions = []            // 清空原有下拉
      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getSubUnitList(params)
        this.subUnitOptions = res.data.map(item => ({
          label: item.subUnitName,
          value: item.subUnitName
        }))
      } catch (e) {
        console.error('获取分包单位下拉失败:', e)
      }
    },
    async getTeamList() {
      this.queryParams.teamName = null // 清空工程已选
      this.teamOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getTeamList(params)
        this.teamOptions = res.data.map(item => ({
          label: item.teamName,   // 工程名称字段
          value: item.teamName
        }))
      } catch (e) {
        console.error('获取班组下拉失败:', e)
      }
    },
    async getSubUnitList() {
      this.queryParams.subUnitName = null // 清空工程已选
      this.subUnitOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getSubUnitList(params)
        this.subUnitOptions = res.data.map(item => ({
          label: item.subUnitName,
          value: item.subUnitName
        }))
      } catch (e) {
        console.error('获取分包单位下拉失败:', e)
      }
    },

    //查看在用设备
    openUserRecords(row) {
      this.openUseRecord = true
      this.dialogUseQuery.teamId = row.teamId
      this.dialogUseQuery.keyWord = ''
      this.dialogUseQuery.proId = row.proId
      this.getUserRecords()
    },
    /** 查询在用设备列表 */
    getUserRecords() {
      getTeamNumSecondListApi(this.dialogUseQuery).then(response => {
        this.useRecordList = response.data.rows
        this.dialogUserTotal = response.data.total
      })
    },

    /** 查询在用设备列表(不分页) */
    getUserRecordsNoPage() {
      getTeamNumSecondListNoPageApi(this.dialogUseQuery).then(response => {
        this.useRecordListNoPage = response.data.rows
      })
    },
    /** 搜索在用按钮操作 */
    handleDialogUseQuery() {
      this.dialogUseQuery.pageNum = 1
      this.getUserRecords()
    },

    //二级页面打印
    async handlePrint() {
          this.openPrint = true
          this.openLoading = true;
          try {
              const res = await getTeamNumSecondListNoPageApi(this.dialogUseQuery)
              this.useRecordListNoPage = res.data.rows
          } catch (error) {
              console.log('🚀 ~ handleLld ~ error:', error)
          } finally {
              this.openLoading = false
          }
        
    },

    //二级页面打印
    print() {
        this.$refs.remarksPrintRef.print()
    },


    //三级页面查看
    handleView(row) {
      this.openUseRecordThree = true
      this.dialogUseQueryThree.agreementId = row.agreementId
      this.dialogUseQueryThree.typeId = row.typeId
      this.dialogUseQueryThree.keyWord = ''
      this.getTeamNumThird()
    },
    getTeamNumThird() {
      getTeamNumThirdApi(this.dialogUseQueryThree).then(response => {
        this.useRecordListThree = response.data.rows
        this.dialogUserThreeTotal = response.data.total
      })
    },
    /** 搜索在用按钮操作 */
    handleDialogUseQueryThree() {
      this.dialogUseQueryThree.pageNum = 1
      this.getTeamNumThird()
    },
    handleResetThree() {
      this.dialogUseQueryThree.pageNum = 1
      this.dialogUseQueryThree.pageSize = 10
      this.$refs.dialogUseQueryThree.resetFields()
      this.dialogUseQueryThree.keyWord = ''
      this.getTeamNumThird()
    },

    handleExport() {
      this.download(
        'material/material_maMachine/exportTeamNumList',
        { ...this.queryParams },
        `班组库存查询_${new Date().getTime()}.xlsx`
      )
    },

    handleDialogUserExport() {
      this.download(
        'material/material_maMachine/exportTeamNumSecondList',
        { ...this.dialogUseQuery },
        `班组库存编码设备查询_${new Date().getTime()}.xlsx`
      )
    },
  }
}
</script>

<style lang="scss" scoped>
.clickText {
  color: #02a7f0;
  cursor: pointer;
}
</style>
