<template>
  <div>
    <a-card size="small" :bordered="false" class="partitionTargetList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="partitionTargetList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules">
          <a-row :gutter="15">
            <a-col :md="5" :sm="24">
              <a-form-model-item label="年份" prop="confYear">
                <a-select
                  id="partitionTargetList-confYear"
                  style="width: 100%"
                  placeholder="请选择年份"
                  :value="queryParam.confYear"
                  @change="changeYear">
                  <a-select-option :id="'partitionTargetList-'+item" v-for="item in years" :value="item" :key="item">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="partitionTargetList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="partitionTargetList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :rowClassName="(record, index) => record.subareaAreaName ==='合计' ? 'last-row':''"
          :scroll="{ y: tableHeight}"
          :showPagination="false"
          :defaultLoadData="false"
          bordered>
          <!-- 1月~12月 -->
          <template
            v-for="col in 12"
            :slot="'month'+col"
            slot-scope="text, record"
          >
            <div :key="col">
              <a-input-number
                style="width:100%;"
                v-if="record.editable"
                size="small"
                :min="0"
                :max="999999999.99"
                placeholder="请输入"
                :precision="2"
                :value="text"
                :id="'partitionTargetList-input-'+record.id"
                @blur="e => handleChange(e.target.value,record, col)"/>
              <template v-else>
                {{ text?toThousands(text):'0.00' }}
              </template>
            </div>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <span v-if="record.editable">
              <a-button
                size="small"
                type="link"
                class="button-info"
                @click="handleSave(record)"
                :id="'partitionTargetList-save-btn'+record.id"
              >
                保存
              </a-button>
              <a-popconfirm title="确定取消吗？" :id="'partitionTargetList-cancel-btn'+record.id" @confirm="() => handleCancel(record)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <a-button
              size="small"
              type="link"
              v-else-if="$hasPermissions('B_dailyReportSettings_edit')&&!record.editable &&record.subareaAreaName!='合计'"
              class="button-info"
              :disabled="editingKey !== ''"
              @click="handleEdit(record)"
              :id="'partitionTargetList-edit-btn'+record.id"
            >
              编辑
            </a-button>
            <span v-else>--</span>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable } from '@/components'
// 接口
import { reportDailyConfList, dailyReportConfSave } from '@/api/reportDailyConf'
export default {
  name: 'PartitionTargetList',
  mixins: [commonMixin],
  components: { STable },
  props: {
    pageType: { //  弹框显示状态
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      toYears: new Date().getFullYear(), // 今年
      editingKey: '', // 按钮是否禁用
      //  查询条件
      queryParam: {
        confType: undefined, // 页面类型
        confYear: new Date().getFullYear() // 年份
      },
      rules: {
        confYear: [{ required: true, message: '请选择年份', trigger: 'change' }]
      },
      dataSources: null, // 表格数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取列表数据  wu分页
        this.queryParam.confType = this.pageType
        const params = Object.assign(parameter, this.queryParam)
        return reportDailyConfList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算表格序号
            for (var i = 0; i < data.length; i++) {
              data[i].no = i + 1
              data[i].editable = false
            }
          }
          this.disabled = false
          this.spinning = false
          this.dataSources = data
          return data
        })
      }
    }
  },
  computed: {
    // 获取年份数据
    years () {
      const years = []
      const lens = (this.toYears - 2023) + 1
      for (let i = 0; i < lens; i++) {
        years.push(this.toYears - i)
      }
      return years
    },
    columns () {
      const _this = this
      const arr = [
        { title: '分区',
          dataIndex: 'subareaAreaName',
          width: '12%',
          align: 'center',
          ellipsis: true,
          customRender: (text, record, index) => {
            const isLastRow = record.no == this.dataSources.length
            return {
              children: text,
              attrs: {
                colSpan: isLastRow ? 2 : 1// 合并前两列
              }
            }
          } },
        { title: '区域负责人',
          dataIndex: 'userName',
          width: '12%',
          align: 'center',
          customRender: (text, record, index) => {
            const isLastRow = record.no == this.dataSources.length
            return {
              children: text || '--',
              attrs: {
                colSpan: isLastRow ? 0 : 1// 合并前两列
              }
            }
          },
          ellipsis: true },
        { title: '1月', dataIndex: 'value01', width: '8%', align: 'right', scopedSlots: { customRender: 'month1' } },
        { title: '2月', dataIndex: 'value02', width: '8%', align: 'right', scopedSlots: { customRender: 'month2' } },
        { title: '3月', dataIndex: 'value03', width: '8%', align: 'right', scopedSlots: { customRender: 'month3' } },
        { title: '4月', dataIndex: 'value04', width: '8%', align: 'right', scopedSlots: { customRender: 'month4' } },
        { title: '5月', dataIndex: 'value05', width: '8%', align: 'right', scopedSlots: { customRender: 'month5' } },
        { title: '6月', dataIndex: 'value06', width: '8%', align: 'right', scopedSlots: { customRender: 'month6' } },
        { title: '7月', dataIndex: 'value07', width: '8%', align: 'right', scopedSlots: { customRender: 'month7' } },
        { title: '8月', dataIndex: 'value08', width: '8%', align: 'right', scopedSlots: { customRender: 'month8' } },
        { title: '9月', dataIndex: 'value09', width: '8%', align: 'right', scopedSlots: { customRender: 'month9' } },
        { title: '10月', dataIndex: 'value10', width: '8%', align: 'right', scopedSlots: { customRender: 'month10' } },
        { title: '11月', dataIndex: 'value11', width: '8%', align: 'right', scopedSlots: { customRender: 'month11' } },
        { title: '12月', dataIndex: 'value12', width: '8%', align: 'right', scopedSlots: { customRender: 'month12' } },
        { title: '合计', dataIndex: 'summation', width: '11%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '11%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 添加数据处理方法
    processData (data, field) {
      let count = 0
      data.forEach((item, index) => {
        if (index === 0 || item[field] !== data[index - 1][field]) {
          count = 1
          // 向后查找相同项
          for (let i = index + 1; i < data.length; i++) {
            if (item[field] === data[i][field]) count++
            else break
          }
          item.rowSpan = count // 设置合并行数
        } else {
          item.rowSpan = 0 // 后续相同项设置为0（不渲染）
        }
      })
      return data
    },
    // 查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.editingKey = ''
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('请选择年份')
          return false
        }
      })
    },
    // 选择查询年份  change
    changeYear (val) {
      this.editingKey = ''
      if (!val) {
        this.queryParam.confYear = void 0
      } else {
        this.queryParam.confYear = val
      }
    },
    // 编辑
    handleEdit (row) {
      this.editingKey = row.no
      row.editable = true
    },
    // 保存
    handleSave (row) {
      row.confYear = this.queryParam.confYear
      dailyReportConfSave(row).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          row.editable = false
          this.editingKey = ''
          this.$refs.table.refresh(true)
        }
      })
    },
    // 取消
    handleCancel (row) {
      row.editable = false
      this.editingKey = ''
      this.$refs.table.refresh(true)
    },
    // input   change事件
    handleChange (val, row, column) {
      const _this = this
      const newColumn = _this.padZero(column)
      row['value' + newColumn] = val || 0
      row.summation = _this.calculateTotal(row)
      // _this.dataSources[column * 1 - 1] = row
    },
    // 补零方法
    padZero (num) {
      return String(num).padStart(2, '0')
    },
    // 计算合计
    calculateTotal (rowData) {
      const keys = Array.from({ length: 12 }, (_, i) => 'value' + this.padZero(i + 1))
      const totalNum = keys.reduce((sum, key) => sum + (Number(rowData[key]) || 0), 0)
      console.log('sdsdsd:', totalNum)
      return totalNum
    },
    //  重置
    resetSearchForm () {
      this.editingKey = ''
      this.queryParam.confType = undefined
      this.queryParam.confYear = new Date().getFullYear()
      this.$refs.ruleForm.resetFields()
      this.$refs.table.refresh(true)
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
      })
      this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 280
    }
  },
  mounted () {
    this.pageInit()
  }
}
</script>
<style lang="less" scoped>
.button-info[disabled] {
  color: gray;
}
/* 最后一行样式 */
/deep/.last-row {
    background: #fafafa !important; /* 灰色背景 */
    /* 固定定位 */
    position: sticky;
    bottom: 0;
    z-index: 2;
  }
/deep/.ant-input-number-handler-wrap {
    display: none;
  }
</style>
