<template>
  <div class="app-container" id="">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 日期范围 -->
      <el-form-item label="领料日期" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="date"
          placeholder="开始日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="">-</el-form-item>
      <el-form-item label="" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="date"
          placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>

      <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="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="输入『 工器具名称 / 领料工程 / 班组长 / 出库人 / 领料单号 』关键字搜索"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 460px"
        />
      </el-form-item>

      <el-form-item label="领料方式" prop="leaseStyle">
        <el-select v-model="queryParams.leaseStyle" placeholder="请选择领料方式" clearable filterable>
          <el-option
            v-for="item in proStatus"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </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">
      <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 label="物资名称" align="center" prop="maTypeName" :show-overflow-tooltip="true" />
      <el-table-column label="规格型号" align="center" prop="typeName" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="预领数量" align="center" prop="preNum" :show-overflow-tooltip="true" /> -->
      <el-table-column label="出库数量" align="center" prop="outNum" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
          <span class="clickText" v-if="scope.row.manageType == '0'" @click="openRecords(scope.row)">
            {{ scope.row.outNum }}
          </span>
          <!-- 否则，直接显示数字 -->
          <span v-else>
            {{ scope.row.outNum }}
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="待出库数量" align="center" prop="pendingNum" :show-overflow-tooltip="true" /> -->
      <el-table-column label="领料日期" align="center" prop="leaseDate" width="100" />
      <el-table-column label="分公司" align="center" prop="impUnitName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="项目部" align="center" prop="departName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="分包单位" align="center" prop="subUnitName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="领料班组" align="center" prop="teamName" width="200" />
      <el-table-column label="领料工程" align="center" prop="projectName" width="200" />
      <el-table-column label="班组长/领料人" align="center" prop="leasePerson" :show-overflow-tooltip="true" />
      <el-table-column label="出库人" align="center" prop="outPerson" :show-overflow-tooltip="true" />
      <el-table-column label="领料单号" align="center" prop="code" :show-overflow-tooltip="true" width="180"/>
      <el-table-column label="领料方式" align="center" prop="leaseStyle" :show-overflow-tooltip="true" width="180"/>
    </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 type="primary" icon="el-icon-refresh" size="mini" @click="handleDialogReset">重置</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="materialName" :show-overflow-tooltip="true" />
        <el-table-column label="规格型号" align="center" prop="typeName" :show-overflow-tooltip="true" />
        <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true" />
        <el-table-column label="出库人员" align="center" prop="outPerson" :show-overflow-tooltip="true" />
        <el-table-column label="出库时间" align="center" prop="outTime" width="100" />
      </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 { getLeaseInfoDetailsApi, getLeaseInfoDetailsNoPageListApi, getSecondLeaseInfoApi,
    getImpUnitListApi, getDepartListByImpUnitApi, getProListByDepartApi, getTeamList, getSubUnitList
 } from '@/api/materialsStation'
import { formatTime } from '@/utils/bonus'

export default {
  name: 'LeaseRecord',
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: '查看',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: null,
        startTime: null,
        endTime: null,
        impUnitName:'',//分公司
        departName:'',//项目部
        subUnitName:'',//分包单位
        teamName:'',//领料班组
        leaseStyle:'',//领料方式
      },

      proStatus:[
        { id: 1, name: '材料站领料' },
        { id: 2, name: '后勤领料' },
      ],

      //在库弹窗
      openRecord: false,
      dialogList: [], //在库编码设备列表
      dialogQuery: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined
      },
      dialogTotal: 0,
      impUnitOptions: [],   // 分公司下拉
      departOptions: [],    // 项目部下拉
      proOptions: [],       // 工程下拉
      subUnitOptions: [],   // 分包单位下拉
      teamOptions: [],      // 班组下拉
    }
  },
  created() {
    const end = new Date()
    let start = new Date()
    start.setMonth(start.getMonth() - 1)
    this.queryParams.startTime = this.format(start)
    this.queryParams.endTime = this.format(end)
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.handleDepartChange()
    this.getTeamList()
    this.getSubUnitList()
    this.getList()
  },
  methods: {
    format(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },

    /** 获取分公司下拉 */
    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)
      }
    },

    // 获取列表
    async getList() {
      this.loading = true
      const params = {
        keyWord: this.queryParams.keyWord,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        impUnitName: this.queryParams.impUnitName,
        departName: this.queryParams.departName,
        proName: this.queryParams.proName,
        subUnitName: this.queryParams.subUnitName,
        teamName: this.queryParams.teamName,
        leaseStyle: this.queryParams.leaseStyle
      }
      const res = await getLeaseInfoDetailsApi(params)
      if (res.data.rows.length > 0) {
        this.tableList = res.data.rows
      } else {
        this.tableList = []
      }
      this.total = res.data.total
      console.log(this.tableList)
      let param = {
        keyWord: this.queryParams.keyWord,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        impUnitName: this.queryParams.impUnitName,
        departName: this.queryParams.departName,
        proName: this.queryParams.proName,
        subUnitName: this.queryParams.subUnitName,
        teamName: this.queryParams.teamName,
        leaseStyle: this.queryParams.leaseStyle
      }
      const response = await getLeaseInfoDetailsNoPageListApi(param)
      let obj = {
        outNum: response.data.outNum || 0,
        preNum: response.data.preNum || 0,
        pendingNum: response.data.pendingNum || 0
      }
      this.tableList.unshift(obj)
      console.log(this.tableList)
      this.loading = false
    },
    indexContinuationForTable(num, size) {
      let number = (num - 1) * size
      console.log(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 = 3
        return { rowspan, colspan }
      }
      // 解决偏移的重要代码
      // 重点在 else if 判断必须加因为合并单元格数据会出现偏移、
      // 否则如果是 第二行 的 第二列 那么隐藏原有第二行 的 第二列的数据使他隐藏
      else if (rowIndex === 0 && columnIndex < 3) {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      const end = new Date()
      let start = new Date()
      start.setMonth(start.getMonth() - 1)
      this.queryParams.startTime = this.format(start)
      this.queryParams.endTime = this.format(end)
      this.resetForm('queryForm')
      this.getImpUnitOptions()
      this.handleImpUnitChange()
      this.handleDepartChange()
      this.getTeamList()
      this.getSubUnitList()
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'material/material_lease_apply_info/exportLeaseInfoDetails',
        {
          ...this.queryParams
        },
        `工器具领料记录_${formatTime(new Date())}.xlsx`
      )
    },
    //查看在库编码数据
    openRecords(row) {
      this.openRecord = true
      this.dialogQuery.keyWord = ''
      this.dialogQuery.typeId = row.typeId
      this.dialogQuery.parentId = row.parentId
      this.getStoreCodeList()
    },
    /** 查询在库编码列表 */
    getStoreCodeList() {
      getSecondLeaseInfoApi(this.dialogQuery).then(response => {
        this.dialogList = response.data.rows
        this.dialogTotal = response.data.total
      })
    },
    /** 搜索在库按钮操作 */
    handleDialogQuery() {
      this.dialogQuery.pageNum = 1
      this.getStoreCodeList()
    },
    handleDialogReset() {
      this.dialogQuery.pageNum = 1
      this.dialogQuery.keyWord = ''
      this.getStoreCodeList()
    },
    handleDialogStoreExport() {
      this.download(
        'material/material_lease_apply_info/exportSecondLeaseInfo',
        { ...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;
}
</style>
