<template>
  <div class="app-container" id="">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <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 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>
        <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">
      <div class="tip-box-wrap">
        <div class="tip-box">
          <div class="tip-num">{{ tipForm.departNum || 0 }}</div>
          <div class="tip-text">项目部总数</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.proNum || 0 }}</div>
          <div class="tip-text">工程总数</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.teamNum || 0 }}</div>
          <div class="tip-text">班组总数</div>
        </div>

        <div class="tip-box tip-box-special">
          <div class="tip-left">
            <div class="tip-text">计件类</div>
          </div>
          <div class="tip-right">
            <div class="tip-right-item">
              <span class="tip-right-text">总保有量：</span>
              <span class="tip-right-number">{{ tipForm.countNum || 0 }}</span>
            </div>
            <div class="tip-right-item">
              <span class="tip-right-text">站内数量：</span>
              <span class="tip-right-number">{{ tipForm.inCountNum || 0 }}</span>
            </div>
            <div class="tip-right-item">
              <span class="tip-right-text">在用数量：</span>
              <span class="tip-right-number">{{ tipForm.useCountNum || 0 }}</span>
            </div>
          </div>
        </div>

        <div class="tip-box tip-box-special">
          <div class="tip-left">
            <div class="tip-text">绳索类</div>
          </div>
          <div class="tip-right">
            <div class="tip-right-item">
              <span class="tip-right-text">总保有量：</span>
              <span class="tip-right-number">{{ tipForm.ropeNum || 0 }}</span>
            </div>
            <div class="tip-right-item">
              <span class="tip-right-text">站内数量：</span>
              <span class="tip-right-number">{{ tipForm.inRopeNum || 0 }}</span>
            </div>
            <div class="tip-right-item">
              <span class="tip-right-text">在用数量：</span>
              <span class="tip-right-number">{{ tipForm.useRopeNum || 0 }}</span>
            </div>
          </div>
        </div>

        <div class="tip-box">
          <div class="tip-num">¥ {{ tipForm.totalPrice || 0 }}</div>
          <div class="tip-text">投入费用（万元）</div>
        </div>

        <!-- <div class="tip-box">
          <div class="tip-num">¥ {{ tipForm.rentPrice || 0 }}</div>
          <div class="tip-text">租赁费用（万元）</div>
        </div> -->

        <!-- <div class="tip-box">
          <div class="tip-num">{{ tipForm.countNum || 0 }}</div>
          <div class="tip-text">计件类总保有量</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.inCountNum || 0 }}</div>
          <div class="tip-text">计件类站内数量</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.useCountNum || 0 }}</div>
          <div class="tip-text">计件类在用数量</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.ropeNum || 0 }}</div>
          <div class="tip-text">绳索类总保有量</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.inRopeNum || 0 }}</div>
          <div class="tip-text">绳索类站内数量</div>
        </div>

        <div class="tip-box">
          <div class="tip-num">{{ tipForm.useRopeNum || 0 }}</div>
          <div class="tip-text">绳索类在用数量</div>
        </div> -->
      </div>
    </el-row>
    <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-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportDetails">导出明细数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="tableList" :max-height="650">
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="55"
        :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <el-table-column label="分公司" align="center" prop="impUnitName" width="140" />
      <el-table-column label="项目部" align="center" prop="departName" width="200" />
      <el-table-column label="工程名称" align="center" prop="proName" width="200" />
      <el-table-column label="分包单位" align="center" prop="subUnitName" width="200">
        <template slot-scope="{ row }">
          <span v-if="row.subUnitName">{{ row.subUnitName }}</span>
          <span v-else>{{ '/' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班组名称" align="center" prop="teamName">
        <template slot-scope="{ row }">
          <span v-if="row.teamName">{{ row.teamName }}</span>
          <span v-else>{{ '站内库存' }}</span>
        </template>
      </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="jiJuType" :show-overflow-tooltip="true" />
      <el-table-column label="计量单位" align="center" prop="unit" :show-overflow-tooltip="true" width="80px"/>
      <el-table-column label="数量" align="center" prop="allNum" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
          <span v-if="scope.row.manageType == '编码' || (scope.row.manageType == '数量' && scope.row.bzFlag == 0)" class="clickText" @click="openRecords(scope.row)">
            {{ scope.row.allNum }}
          </span>
          <!-- 否则，直接显示数字 -->
          <span v-else>
            {{ scope.row.allNum }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="原值(万元)" align="center" prop="totalPrice" :show-overflow-tooltip="true"/>
    </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-button icon="el-icon-refresh" size="mini" @click="resetDialogQuery">重置</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="maCode" :show-overflow-tooltip="true">
          <template slot-scope="{ row }">
            <span>{{ row.maCode || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="storeNum" :show-overflow-tooltip="true" />
        <el-table-column label="操作人" align="center" prop="creator" :show-overflow-tooltip="true" />
        <el-table-column label="出库时间" align="center" prop="outTime" :show-overflow-tooltip="true" width="180" />
        <el-table-column label="班组" align="center" prop="teamName" :show-overflow-tooltip="true" />
        <el-table-column label="工程名称" align="center" prop="proName" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="是否直转" align="center" prop="directFlag" :show-overflow-tooltip="true" width="80">
          <template slot-scope="scope">
            {{ scope.row.directFlag == "0" ? '是' : scope.row.directFlag == "1" ? '否' : scope.row.directFlag }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="dialogTotal > 0"
        :total="dialogTotal"
        :page.sync="dialogQuery.pageNum"
        :limit.sync="dialogQuery.pageSize"
        @pagination="getStoreCodeList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getProTotalListApi,
  getStorageInfoListApi,
  getRetainedEquipmentListApi,
  getImpUnitListApi, getDepartListByImpUnitApi, getProListByDepartApi, getTeamList, getSubUnitList
} from '@/api/materialsStation'
import {getMaterialTypeList} from "@/api/ma/device";
export default {
  name: 'EquipmentRecord',
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: '查看',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        impUnitName: null,
        departName: null,
        proName: null,
        subUnitName: null,
        teamName: null,
        typeName: null, //物资名称
        typeModelName: null, //规格型号
        jiJuType: null        // 机具类型 (1施工机具 2安全工器具)
      },
      tipForm: {
        departNum: 0, // 项目部总数
        proNum: 0, // 工程总数
        teamNum: 0, // 班组总数
        allNum: 0, // 总保有量
        inNum: 0, // 站内数量
        useNum: 0, // 在用数量
        countNum:0,
        ropeNum:0,
        inCountNum:0,
        inRopeNum:0,
        useCountNum:0,
        useRopeNum:0,
      },

      //在库弹窗
      openRecord: false,
      dialogList: [], //在库编码设备列表
      dialogQuery: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined
      },
      dialogTotal: 0,
      impUnitOptions: [],   // 分公司下拉
      departOptions: [],    // 项目部下拉
      proOptions: [],       // 工程下拉
      subUnitOptions: [],   // 分包单位下拉
      teamOptions: [],      // 班组下拉
      materialNameList: [],
      materialModelList: [],
    }
  },
  created() {
    this.getList()
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.handleDepartChange()
    this.getTeamList()
    this.getSubUnitList()
    this.getDeviceType()
  },
  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 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
        }))
        if (this.queryParams.subUnitName) {
          this.teamOptions = this.teamOptions.filter(item => item.value !== '站内库存')
        }
      } 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
      const params = {
        ...this.queryParams
      }
      try {
        const res = await getRetainedEquipmentListApi(params)
        this.tableList = res.data.rows || []
        console.log('🚀 ~ getList ~ this.tableList:', this.tableList)
        this.total = res.data.total || 0
        const totalInfo = await getProTotalListApi(params)
        this.tipForm = totalInfo.data
        console.log('🚀 ~ getList ~ this.tableList:', this.tableList)
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
      this.handleMaModel()
      this.getImpUnitOptions()
      this.handleImpUnitChange()
      this.handleDepartChange()
      this.getTeamList()
      this.getSubUnitList()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'material/material_maMachine/exportRetainedEquipmentList',
        {
          ...this.queryParams
        },
        `工器具台账_${new Date().getTime()}.xlsx`
      )
    },
    handleExportDetails() {
      this.download(
        'material/material_maMachine/exportRetainedEquipmentDetails',
        {
          ...this.queryParams
        },
        `工器具台账详情_${new Date().getTime()}.xlsx`
      )
    },
    //查看在库编码数据
    openRecords(row) {
      this.dialogList = []
      this.dialogTotal = 0
      this.dialogQuery.pageNum = 1
      this.dialogQuery.pageSize = 10
      this.dialogQuery.keyWord = ''
      this.dialogQuery.typeId = row.typeId
      this.dialogQuery.proId = row.proId
      this.dialogQuery.teamId = row.teamId || ''
      this.dialogQuery.subFlag = row.subUnitName == '分包直领' ? 0 : null
      this.openRecord = true
      this.getStoreCodeList()
    },
    /** 查询在库编码列表 */
    async getStoreCodeList() {
      try {
        this.loading = true
        const res = await getStorageInfoListApi(this.dialogQuery)
        this.dialogList = res.data.rows || []
        this.dialogTotal = res.data.total || 0
      } catch (error) {
        console.log('🚀 ~ getStoreCodeList ~ error:', error)
      } finally {
        this.loading = false
      }
    },
    /** 搜索在库按钮操作 */
    handleDialogQuery() {
      this.dialogQuery.pageNum = 1
      this.dialogQuery.pageSize = 10
      this.getStoreCodeList()
    },
    resetDialogQuery() {
      this.dialogQuery.pageNum = 1
      this.dialogQuery.pageSize = 10
      this.dialogQuery.keyWord = ''
      this.getStoreCodeList()
    },
    handleDialogStoreExport() {
      this.download(
        'material/material_maMachine/exportStorageInfoList',
        { ...this.dialogQuery },
        `设备编码详情_${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;
}
.tip-box-wrap {
  display: flex;
  justify-content: space-between;
  .tip-box {
    padding: 10px 25px;
    background: #4cb1f9;
    border-radius: 5px;
    color: #fff;
    text-align: center;
    .tip-num {
      font-size: 28px;
    }
  }
}

.tip-box-special {
  display: flex;
  align-items: center;
  padding: 15px;
  width: 290px; /* 可以根据需要调整宽度 */
}

.tip-left {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-right: 15px;
}

.tip-right {
  flex: 1;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

}

.tip-right-item {
  color: #fff;
  text-align: left;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tip-right-text {
  text-align: right;
}

.tip-right-number {
  text-align: right;
  min-width: 60px; /* 可以根据实际情况调整最小宽度 */
}
</style>
