<template>
  <div class="app-container">
    <el-row style="width: 100%">
      <el-col :span="18">
        <el-button type="primary" size="mini" @click="handleExport1" :disabled="leaseList && leaseList.length == 0 " >租赁明细导出</el-button>
        <el-button type="primary" size="mini" @click="handleExport3" :disabled="repairList && repairList.length == 0 ">维修明细导出</el-button>
        <el-button type="primary" size="mini" @click="handleExport4" :disabled="scrapList && scrapList.length == 0 ">报废明细导出</el-button>
        <el-button type="primary" size="mini" @click="handleExport2" :disabled="loseList && loseList.length == 0 ">丢失明细导出</el-button>
        <el-button type="primary" size="mini" @click="handleExport5" :disabled="reducList && reducList.length == 0 ">减免明细导出</el-button>
        <el-button type="warning" size="mini" @click="handleExportAll">全部明细导出</el-button>
      </el-col>
    </el-row>

    <div style="margin-top: 20px">
      <div class="tabelAllTop">
        <div class="costTop">结算费用</div>
      </div>
      <div class="tabelAllTopUnit">
        <div class="costTopUnit">结算单位</div>
        <div class="costRightUnit">
          {{ unitName }}
        </div>
      </div>
        <div class="tabelAllTopUnit">
          <div class="costTopUnit">结算工程</div>
          <div class="costRightUnit">
            {{ projectName }}
          </div>
        </div>
        <div class="tabelAllTopUnit">
          <div class="costTopUnit">出场日期</div>
          <div class="costRightUnit">
            {{ actualTimeAndName }}
          </div>
        </div>
      <el-table :data="leaseList" max-height="500px">
          <el-table-column label="租赁（超期）费用明细" align="center" >
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="租赁单价" align="center" prop="leasePrice" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.leasePrice">
                {{ scope.row.leasePrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="租赁数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="领料日期" align="center" prop="startTime" :show-overflow-tooltip="true" />
            <el-table-column label="归还日期 " align="center" prop="endTime" :show-overflow-tooltip="true" />
            <el-table-column label="租赁天数" align="center" prop="leaseDays" :show-overflow-tooltip="true"/>
            <el-table-column label="出场日期" align="center" prop="actualExitTime" :show-overflow-tooltip="true"/>
            <el-table-column label="超期日期" align="center" prop="overTime" :show-overflow-tooltip="true"/>
            <el-table-column label="超期天数" align="center" prop="overDay" :show-overflow-tooltip="true"/>
            <el-table-column label="超期费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
      </el-table>

      <div class="tabelAll">
        <div class="columnAllNum">费用小计：</div>
        <div class="columnAll">
          {{ leaseCost }}
        </div>
      </div>
    </div>

    <div>
      <el-table :data="repairList" max-height="500px">
          <el-table-column label="维修费用明细" align="center" >
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="维修数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="是否收费" align="center" prop="partType" :show-overflow-tooltip="true" />
            <el-table-column label="维修费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
      </el-table>
      <div class="tabelAll">
        <div class="columnAllNum">费用小计：</div>
        <div class="columnAll">
          {{ repairCost }}
        </div>
      </div>
    </div>

    <div>
      <el-table :data="scrapList" max-height="500px">
          <el-table-column label="报废费用明细" align="center">
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="报废数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="是否收费" align="center" prop="partType" :show-overflow-tooltip="true" />
            <el-table-column label="报废费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
      </el-table>
      <div class="tabelAll">
        <div class="columnAllNum">费用小计：</div>
        <div class="columnAll">
          {{ scrapCost }}
        </div>
      </div>
    </div>

    <div>
      <el-table :data="loseList" max-height="500px">
          <el-table-column label="未归还费用明细" align="center">
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="丢失数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="原值（元）" align="center" prop="buyPrice" :show-overflow-tooltip="true" >
              <template slot-scope="scope" v-show="scope.row.buyPrice">
                {{ scope.row.buyPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="未归还费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
      </el-table>
      <div class="tabelAll">
        <div class="columnAllNum">费用小计：</div>
        <div class="columnAll">
          {{ loseCost }}
        </div>
      </div>
    </div>

    <div>
      <el-table :data="reducList" max-height="500px">
          <el-table-column label="减免费用明细" align="center">
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modeName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="租赁单价" align="center" prop="leasePrice" :show-overflow-tooltip="true" />
            <el-table-column label="减免数量" align="center" prop="reduceNum" :show-overflow-tooltip="true" />
            <el-table-column label="减免开始日期" align="center" prop="startTime" :show-overflow-tooltip="true" />
            <el-table-column label="减免结束日期" align="center" prop="endTime" :show-overflow-tooltip="true" />
            <el-table-column label="减免天数" align="center" prop="days" :show-overflow-tooltip="true" />
            <el-table-column label="减免原因" align="center" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="减免费用（元）" align="center" prop="leaseMoney" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.leaseMoney">
                {{ scope.row.leaseMoney.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
      </el-table>
      <div class="tabelAllBottom">
        <div class="columnAllNum">费用小计：</div>
        <div class="columnAll">
          {{ reducCost }}
        </div>
      </div>
      <div class="tabelAllBottom">
        <div class="columnAllNum">合计：</div>
        <div class="columnAll">
          {{ costAll.toFixed(2) }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSltInfo, getClzSettledInfo } from '@/api/cost/cost'

export default {
  name: '',
  dicts: [],
  props: {
    row: {
      type: [String]
    }
  },
  data() {
    return {
      // 往来单位数据
      unitList: [],
      // 工程数据
      projectList: [],
      leaseList: [], //租赁费用列表
      leaseCost: 0,
      repairList: [], //维修费用列表
      repairCost: 0,
      scrapList: [], //报废费用列表
      scrapCost: 0,
      loseList: [], //丢失费用列表
      loseCost: 0,
      reducList: [], //减免费用列表
      reducCost: 0,
      costAll: 0,
      deptName: undefined,
      applyList: [],
      projectName: undefined, //结算工程
      unitName: undefined, //结算单位
      actualTimeAndName: '', //实际时间和对应的班组名称
    }
  },
  mounted() {
    console.log('33333333333', this.row)
    let arr = JSON.parse(this.row)
    this.rowData = arr
    this.getDataAll()
  },
  methods: {
    //获取单位类型 ,getUnitList, getProjectList
    getUnitList() {
      getUnitList().then(response => {
        this.unitList = response.data
      })
    },
    getProjectList() {
      getProjectList().then(response => {
        this.projectList = response.data
      })
    },
    /** 查询列表 */
    getDataAll() {
      // 后端仅需 code 参数，这里优先取 sltApplyCode，若为数组则取第一个
      const code = Array.isArray(this.rowData)
        ? (this.rowData[0]?.sltApplyCode || this.rowData[0]?.code)
        : (this.rowData?.sltApplyCode || this.rowData?.code)

      getClzSettledInfo(code).then(response => {
        const dataArray = Array.isArray(response.data) ? response.data : [response.data]

        // 初始化
        this.leaseList = []
        this.repairList = []
        this.scrapList = []
        this.loseList = []
        this.reducList = []
        this.reducCost = 0

        const projectNames = []
        const unitNames = []
        const actualTimeAndNames = [] // 用于存储实际时间和对应的班组名称

        // 合并各项列表，同时为明细补充单位名称以便显示
        dataArray.forEach(item => {
          if (!item) return
          const currentUnitName = item.unitName || ''
          const currentProjectName = item.projectName || ''
          if (currentUnitName) unitNames.push(currentUnitName)
          if (currentProjectName) projectNames.push(currentProjectName)

          if (Array.isArray(item.leaseList) && item.leaseList.length) {
            const listWithUnit = item.leaseList.map(x => ({ ...x, unitName: x.unitName || currentUnitName }))
            this.leaseList = [...this.leaseList, ...listWithUnit]
          }
          if (Array.isArray(item.repairList) && item.repairList.length) {
            const listWithUnit = item.repairList.map(x => ({ ...x, unitName: x.unitName || currentUnitName }))
            this.repairList = [...this.repairList, ...listWithUnit]
          }
          if (Array.isArray(item.scrapList) && item.scrapList.length) {
            const listWithUnit = item.scrapList.map(x => ({ ...x, unitName: x.unitName || currentUnitName }))
            this.scrapList = [...this.scrapList, ...listWithUnit]
          }
          if (Array.isArray(item.loseList) && item.loseList.length) {
            const listWithUnit = item.loseList.map(x => ({ ...x, unitName: x.unitName || currentUnitName }))
            this.loseList = [...this.loseList, ...listWithUnit]
          }
          if (Array.isArray(item.reductionList) && item.reductionList.length) {
            const listWithUnit = item.reductionList.map(x => ({ ...x, unitName: x.unitName || currentUnitName }))
            this.reducList = [...this.reducList, ...listWithUnit]
          }
          if(item.unitName && item.actualExitTime){
              const timeAndName = `${item.unitName} ( ${item.actualExitTime} )`;
              // 检查是否已存在该元素，不存在才添加
              if(!actualTimeAndNames.includes(timeAndName)) {
                actualTimeAndNames.push(timeAndName);
              }
          }else if(item.unitName && !item.actualExitTime){
              const timeAndName = `${item.unitName} ( 暂无 )`;
              // 检查是否已存在该元素，不存在才添加
              if(!actualTimeAndNames.includes(timeAndName)) {
                actualTimeAndNames.push(timeAndName);
              }
          }
        })

        // 单位/工程名展示：去重后拼接
        const unique = arr => Array.from(new Set(arr)).filter(Boolean)
        this.unitName = unique(unitNames).join('，')
        this.projectName = unique(projectNames).join('，')
        this.actualTimeAndName = unique(actualTimeAndNames).join(', ')
        // 费用汇总
        const sumCosts = list => list.reduce((s, x) => s + (Number(x.costs) || 0), 0)
        this.leaseCost = this.countCost(this.leaseList)
        this.loseCost = this.countCost(this.loseList)
        this.repairCost = sumCosts(this.repairList).toFixed(2)
        this.scrapCost = sumCosts(this.scrapList).toFixed(2)
        if (this.reducList && this.reducList.length) {
          this.reducList.forEach(x => {
            this.reducCost = Number(this.reducCost) + Number(x.leaseMoney || 0)
          })
        }

        // relations 直接取第一项或合并（保持兼容：若存在则做基本数值归一）
        this.applyList = (dataArray[0] && Array.isArray(dataArray[0].relations)) ? dataArray[0].relations : []
        this.applyList.forEach(item => {
          item.leaseCost = Number(item.leaseCost)
          item.repairCost = Number(item.repairCost)
          item.scrapCost = Number(item.scrapCost)
          item.loseCost = Number(item.loseCost)
          item.cost =
            Number(item.leaseCost) +
            Number(item.repairCost) +
            Number(item.scrapCost) +
            Number(item.loseCost) +
            Number(item.reductionCost) +
            Number(item.addCost) -
            Number(item.subCost)
        })

        const costSum =
          Number(this.leaseCost) +
          Number(this.repairCost) +
          Number(this.scrapCost) +
          Number(this.loseCost) -
          Number(this.reducCost)
        this.costAll = costSum
        this.subCostFlag = costSum
      })
    },
    //计算金额1
    countCost(list) {
      let arrCost = 0
      list.forEach(item => {
        // 后端返回的明细中 costs 可能为 null，这里做安全求和
        const costs = Number(item.costs || 0)
        arrCost = arrCost + costs
      })
      return arrCost.toFixed(2)
    },
    //el-table-合计总费用
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 9) {
          sums[index] = '最终费用'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        // 只对amount这一列进行总计核算。
        if (column.property === 'cost') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            // sums[index] += ' 元';
          } else {
            sums[index] = '---'
          }
        }
      })
      return sums
    },
    countNum(row) {
      row.cost =
        Number(row.leaseCost) +
        Number(row.repairCost) +
        Number(row.scrapCost) +
        Number(row.loseCost) +
        Number(row.addCost || 0) -
        Number(row.subCost || 0)
    },

    //返回
    handleBack() {
      this.$emit('goBackPage')
    },
    /** 导出按钮操作 */
    //租赁
    handleExport1() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let data = {unitId:this.rowData[0].unitId,projectId:this.rowData[0].projectId,sltApplyCode:this.rowData[0].sltApplyCode}
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportLeaseReview', { ...params }, `租赁费用明细_${currentTime}.xlsx`)
    },
    //丢失
    handleExport2() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let data = {unitId:this.rowData[0].unitId,projectId:this.rowData[0].projectId,sltApplyCode:this.rowData[0].sltApplyCode}
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportLoseReview', { ...params }, `丢失费用明细_${currentTime}.xlsx`)
    },
    // 维修
    handleExport3() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/slt_agreement_info/exportRepair', { ...params }, `维修费用明细_${currentTime}.xlsx`)
    },
    //报废
    handleExport4() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/slt_agreement_info/exportScrap', { ...params }, `报废费用明细_${currentTime}.xlsx`)
    },
    handleExport5() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/slt_agreement_info/exportReduction', { ...params }, `减免费用明细_${currentTime}.xlsx`)
    },

    handleExportAll() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let data = {unitId:this.rowData[0].unitId,projectId:this.rowData[0].projectId,sltApplyCode:this.rowData[0].sltApplyCode}
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportAllReview', { ...params }, `全部费用明细_${currentTime}.xlsx`)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 80px !important;
  margin-bottom: 10px;
}
.tabelAllTop {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  height: 50px;
  background-color: #f8f8f9;
  border-left: none;
  border-bottom: none;
  .costTop {
    display: flex;
    padding: 5px;
    border-left: 1px solid #dfe6ec;
    align-items: center;
    text-align: center;
    justify-content: center; /* 将内容对齐到中间 */
    width: 100%;
    font-weight: bold; /* 添加字体加粗样式 */
  }
}
.tabelAllTopUnit {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  height: 50px;
  background-color: #f8f8f9;
  border-bottom: none;
  .costTopUnit {
    display: flex;
    padding: 5px;
    width: 21.4%;
    border-left: none;
    align-items: center;
    text-align: center;
    justify-content: center; /* 将内容对齐到中间 */
  }
  .costRightUnit {
    display: flex;
    padding: 5px;
    border-left: 1px solid #dfe6ec;
    text-align: center;
    align-items: center;
    width: 100%;
    justify-content: center; /* 将内容对齐到中间 */
    // padding-left: 20px; /* 添加左内边距 */
  }
}
.tabelAll {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  border-bottom: 1px solid #dfe6ec;
  border-top: none;
  margin-bottom: 15px;
}
.tabelAllBottom {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  border-bottom: 1px solid #dfe6ec;
  border-top: none;
}
.columnAll {
  display: flex;
  padding: 5px;
  border-left: 1px solid #dfe6ec;
  text-align: center;
  align-items: center;
  width: 100%;
  justify-content: flex-end; /* 将内容对齐到右侧 */
  margin-right: 60px; /* 添加右边距 */
}
.columnAllNum {
  padding: 5px;
  text-align: center;
  width: 21.4%;
  border-left: none;
}
/* 最后一列无右边框 */
.tabelAll .column:last-child {
  border-right: none;
}
</style>
