<template>
  <div class="app-container" id="">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <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"
        >
          <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="typeName">
        <el-select
          v-model="queryParams.typeName"
          placeholder="请选择物资名称"
          clearable
          filterable
          style="width: 240px"
          @change="handleMaModel"
        >
          <el-option v-for="item in materialNameList" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>

      <el-form-item label="规格型号" prop="typeModelName">
        <el-select
          v-model="queryParams.typeModelName"
          placeholder="请选择规格型号"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option v-for="item in materialModelList" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="机具类型" prop="jiJuType">
        <el-select v-model="queryParams.jiJuType" placeholder="请选择机具类型" clearable style="width: 240px">
          <el-option label="施工机具" :value="1" />
          <el-option label="安全工器具" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="计量单位" prop="unitValue">
        <el-select
          v-model="queryParams.unitValue"
          placeholder="请选择计量单位"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option v-for="item in unitNameList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.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="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="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="tableList" :span-method="objectSpanMethod" :max-height="650">
      <el-table-column label="序号" align="center" type="index">
        <template scope="scope">
          <span v-if="scope.$index == 0">合计：</span>
          <span v-else>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(column, index) in tableColumns"
        :show-overflow-tooltip="!column.unShowTooltip"
        :key="index"
        :label="column.label"
        :prop="column.prop"
        :width="column.width"
        align="center"
      >
        <template v-slot="{ row }" v-if="column.prop === 'storeNum'">
          <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
          <!-- <span
            class="clickText"
            v-if="row.manageType == '编码' && row.storeNum > 0 && $index != 0"
            @click="openRecords(row)"
          >
            {{ row.storeNum }}
          </span> -->
          <!-- 否则，直接显示数字 -->
          <span>{{ row.storeNum }}</span>
        </template>

        <template v-slot="{ row, $index }" v-else-if="column.prop === 'useNum'">
          <span v-if="row.useNum > 0 && $index != 0" class="clickText" @click="openUserRecords(row)">
            {{ row.useNum }}
          </span>
          <!-- 否则，直接显示数字 -->
          <span v-else>{{ row.useNum }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      @pagination="getList"
    />

    <!-- 在库编码设备弹窗-->
    <el-dialog :title="title" :visible.sync="openRecord" width="1200px" append-to-body>
      <el-form :model="dialogQuery" ref="dialogQuery" size="small" :inline="true" label-width="80px">
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="dialogQuery.keyWord"
            placeholder="请输入关键字"
            clearable
            :maxlength="30"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" size="mini" @click="handleDialogStoreExport">导出</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="dialogList">
        <el-table-column
          label="序号"
          align="center"
          width="80"
          type="index"
          :index="indexContinuation(dialogQuery.pageNum, dialogQuery.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="buyPrice" :show-overflow-tooltip="true" />
        <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true" />
        <el-table-column label="操作人" align="center" prop="inputUser" :show-overflow-tooltip="true" />
        <el-table-column label="入库时间" align="center" prop="inputTime" :show-overflow-tooltip="true" />
      </el-table>
      <pagination
        v-show="dialogTotal > 0"
        :total="dialogTotal"
        :page.sync="dialogQuery.pageNum"
        :limit.sync="dialogQuery.pageSize"
        @pagination="getStoreCodeList"
      />
    </el-dialog>
    <!-- 在用编码设备弹窗-->
    <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>

      <el-table v-loading="isDlgLoading" :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="subUnitName" :show-overflow-tooltip="true" />
        <el-table-column label="班组名称" align="center" prop="teamName" :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="leaseNum" :show-overflow-tooltip="true" />
        <el-table-column label="退料数量" align="center" prop="backNum" :show-overflow-tooltip="true" />
        <el-table-column label="在用数量" align="center" prop="useNum" :show-overflow-tooltip="true" />
      </el-table>

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

<script>
import {
  getImpUnitListApi,
  getDepartListByImpUnitApi,
  getProListByDepartApi,
  getTeamList,
  getSubUnitList,
  getStorageInfoListApi,
  getUseDemandAndSupplyApi,
  getDemandAndSupplyApi,
  getDemandAndSupplyNoPageApi
} from '@/api/materialsStation'
import {getMaterialTypeList} from '@/api/ma/device'

export default {
  name: 'SupplyDemandBalance',
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: false,
      isDlgLoading: false,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: '查看',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      tableColumns: [
        { label: '分公司', prop: 'impUnitName', unShowTooltip: true },
        { label: '项目部', prop: 'departName', unShowTooltip: true },
        { label: '工程名称', prop: 'proName', unShowTooltip: true },
        { label: '物资名称', prop: 'typeName', width: 180 },
        { label: '规格型号', prop: 'typeModelName', width: 160 },
        { label: '机具类型', prop: 'jiJuType', width: 100 },
        { label: '计量单位', prop: 'unit', width: 100 },
        { label: '业务需求数量', prop: 'businessNum',width: 130 },
        { label: '实际供应数量', prop: 'supplyNum',width: 130 },
        { label: '已退数量', prop: 'backNum', width: 130 },
        { label: '在库数量', prop: 'storeNum',width: 130 },
        { label: '在用数量', prop: 'useNum', width: 130 }
      ],
      // 主表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: null,
        departName: null,
        proName: null,
        subUnitName: null,
        typeName: null, //物资名称
        typeModelName: null, //规格型号
        jiJuType: null, // 机具类型 (1施工机具 2安全工器具)
        unitValue: null
      },
      impUnitOptions: [], // 分公司下拉
      departOptions: [], // 项目部下拉
      proOptions: [], // 工程下拉
      subUnitOptions: [], // 分包单位下拉
      materialNameList: [], // 物资名称
      materialModelList: [], // 规格型号
      unitNameList: [
        { label: '计件', value: 0 },
        { label: '绳索', value: 1 }
      ], // 单位下拉

      //在库弹窗
      openRecord: false,
      dialogList: [], //在库编码设备列表
      dialogQuery: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        agreementIds: undefined,
      },
      dialogTotal: 0,
      //在用弹窗
      openUseRecord: false,
      dialogUseQuery: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined
      },
      useRecordList: [], //在用设备列表
      dialogUserTotal: 0
    }
  },
  created() {
    const query = this.$route.query || {}
    console.log('🚀 ~ created ~ query:', query)
    this.queryParams.proId = query.proId || ''
    this.queryParams.proCenter = query.proCenter || ''
    this.getList()
    this.getImpUnitOptions()
    this.handleDepartChange()
    this.getSubUnitList()
    this.getDeviceType()
    this.handleImpUnitChange()
  },
  methods: {
    /** 获取分公司下拉 */
    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 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)
      }
    },
    getDeviceType() {
      getMaterialTypeList({ level: 3, skipPermission: 1 }).then(response => {
        let matNameRes = response.data
        this.materialNameList = matNameRes.map(item => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
      getMaterialTypeList({ level: 4, skipPermission: 1 }).then(response => {
        let matModelRes = response.data
        this.materialModelList = matModelRes.map(item => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },
    // change设备类型
    handleMaModel(e) {
      this.queryParams.typeModelName = null
      this.materialModelList = []
      let typeId = null
      if (!e) {
        typeId = null
      } else {
        typeId = this.materialNameList.find(item => item.label == e).value
      }
      console.log('🚀 ~ handleMaModel ~ typeId:', typeId)
      getMaterialTypeList({ level: 4, skipPermission: 1, typeId }).then(response => {
        let matModelRes = response.data
        this.materialModelList = matModelRes.map(item => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },
    // 获取列表
    async getList() {
      this.loading = true
      try {
        const params = {
          ...this.queryParams
        }
        const res = await getDemandAndSupplyApi(params)
        this.tableList = res.data.rows || []
        this.total = res.data.total || 0
        const response = await getDemandAndSupplyNoPageApi(params)
        let obj = {
          ...response.data,
          // businessNum: response.data.businessNum || response.data.totalBusinessNum,
          // supplyNum: response.data.supplyNum,
          // storeNum: response.data.storeNum,
          // useNum: response.data.useNum
        }
        this.tableList.unshift(obj)

        console.log('🚀 ~ getList ~ this.tableList:', this.tableList)
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    indexContinuationForTable(num, size) {
      let number = (num - 1) * size
      console.log('🚀 ~ indexContinuationForTable ~ number:', number)
      if (number == 0) {
        return '合计'
      } else {
        return number
      }
    },
    // 合并单元格 rowIndex=行数  columnIndex=列数
    // 这里是合并table的除表头外的第一行的第二列 + 除表头外的第二行的第二列
    // 注意列数和行数从 0 开始
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0 && columnIndex == 0) {
        let rowspan = 1 // 合并行数
        let colspan = 5 // 合并列数
        return { rowspan, colspan }
      }
      // 解决偏移的重要代码
      // 重点在 else if 判断必须加因为合并单元格数据会出现偏移、
      // 否则如果是 第二行 的 第二列 那么隐藏原有第二行 的 第二列的数据使他隐藏
      else if (rowIndex === 0 && columnIndex < 5) {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'material/material_maMachine/exportDemandAndSupply',
        {
          ...this.queryParams
        },
        `材料站供需平衡表_${new Date().getTime()}.xlsx`
      )
    },
    //查看在库编码数据
    openRecords(row) {
      this.openRecord = true
      this.dialogQuery.keyWord = ''
      this.dialogQuery.typeId = row.typeId
      this.dialogQuery.proId = row.proId
      this.dialogQuery.agreementIds = row.agreementIds
      this.getStoreCodeList()
    },
    /** 查询在库编码列表 */
    getStoreCodeList() {
      getStorageInfoListApi(this.dialogQuery).then(response => {
        this.dialogList = response.data.rows
        this.dialogTotal = response.data.total
      })
    },
    /** 搜索在库按钮操作 */
    handleDialogQuery() {
      this.dialogQuery.pageNum = 1
      this.getStoreCodeList()
    },
    handleDialogStoreExport() {
      this.download(
        'material/material_maMachine/exportStorageInfo',
        { ...this.dialogQuery },
        `站内库存查询_在库设备_${new Date().getTime()}.xlsx`
      )
    },
    // ------------------
    //查看在用设备
    openUserRecords(row) {
      this.openUseRecord = true
      this.dialogUseQuery.typeId = row.typeId
      this.dialogUseQuery.keyWord = ''
      this.dialogUseQuery.proId = row.proId
      this.getUserRecords()
    },
    /** 查询在用设备列表 */
    getUserRecords() {
      this.isDlgLoading = true
      getUseDemandAndSupplyApi(this.dialogUseQuery).then(response => {
        this.isDlgLoading = false
        this.useRecordList = response.data.rows
        this.dialogUserTotal = response.data.total
      }).catch(() => {
        this.isDlgLoading = false
      })
    },
    /** 搜索在用按钮操作 */
    handleDialogUseQuery() {
      this.dialogUseQuery.pageNum = 1
      this.getUserRecords()
    },
    handleDialogUserExport() {
      this.download(
        'material/material_maMachine/exportUseDemandAndSupply',
        { ...this.dialogUseQuery },
        `材料站供需平衡表_在用设备_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}
.clickText {
  color: #02a7f0;
  cursor: pointer;
}
</style>
