<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-position="left" label-width="135px">
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">救援收费标准明细</div>
          </div>
        </div>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="addEditForm.name" clearable placeholder="请输入队伍名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="车类" prop="homeworkVehicles">
              <el-radio-group v-model="addEditForm.homeworkVehicles">
                <el-radio v-for="item in carColourList" :key="item.value"
                          :label="item.value"
                          :value="item.value"
                          border
                >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="加收项上限" prop="upperLimit">
              <el-input v-model="addEditForm.upperLimit" clearable placeholder="请输入加收项上限"
                        @input="handleUpperLimitInput"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="描述" prop="remarks">
              <el-input
                v-model="addEditForm.remarks"
                :rows="2"
                placeholder="请输入内容"
                type="textarea">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  拖车部分      -->
        <div v-if="addEditForm.homeworkVehicles === '1'" class="aaa">
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">基础项</div>
            </div>
          </div>
          <div>
            <fieldset>
              <el-table :data="addEditForm.rescueFeeStandardDetailsBenchmarkList"
                        style="width: 100%">
                <el-table-column
                  align="left"
                  label="车型"
                  prop="carCategory" width="120" />
                <el-table-column align="center" label="基价(元)" prop="benchmarkPrice" width="120">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.benchmarkPrice"
                      clearable
                      placeholder="请输入基价"
                      @input="handleNumberInput(scope.row, 'benchmarkPrice')"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="overtravelFees"
                                 width="180">
                  <template slot="header">
                    <el-tooltip :content="'每增施1公里加收(不足1公里按1公里计算)'" effect="dark" placement="top">
                      <span class="label-text">每增施1公里加收(不足1公里按1公里计算)</span>
                    </el-tooltip>
                  </template>
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.overtravelFees"
                      clearable
                      placeholder="请输入加收金额"
                      @input="handleNumberInput(scope.row, 'overtravelFees')"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="备注" prop="remarks"
                                 width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remarks"
                      clearable
                      placeholder="请输入备注"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" show-overflow-tooltip width="200">
                  <template slot-scope="scope">
                    <el-link :disabled="btnLoading" :underline="false" type="danger"
                             @click="handleDelete(scope.$index, scope.row)">
                      删除
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </fieldset>
          </div>
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">加收项（每次因特殊情况累计加收比例不超过50%）</div>
            </div>
          </div>
          <div>
            <fieldset>
              <el-table :cell-class-name="tableCellClassName" :data="addEditForm.rescueFeeStandardDetailsAdditionalList"
                        :summary-method="getSummaries"
                        show-summary
                        style="width: 120%">
                <el-table-column align="left" label="加收项" prop="additionalName" width="120" />
                <el-table-column align="center" label="加收比例(%)" prop="overtravelProportion" width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.overtravelProportion"
                      :formatter="(value) => value + '%'"
                      clearable
                      placeholder="请输入加收比例"
                      @input="handleInput(scope.row, 'overtravelProportion')"
                    />
                    <!-- 显示时添加 % -->
                  </template>
                </el-table-column>
                <el-table-column align="center" label="备注" prop="remarks"
                                 width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remarks"
                      clearable
                      placeholder="请输入备注"
                    />
                  </template>
                </el-table-column>
                <!--              <el-table-column align="left" label="每增施1公里加收(不足1公里按1公里计算)" prop="phone" width="500" />-->
                <el-table-column align="center" label="操作" min-width="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-link :disabled="btnLoading" :underline="false" type="danger"
                             @click="handleDeleteother(scope.$index, scope.row)">
                      删除
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </fieldset>
          </div>

        </div>
        <!--  吊车部分      -->
        <div v-if="addEditForm.homeworkVehicles === '2'" class="bbb">
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">基础项</div>
            </div>
          </div>
          <div>
            <fieldset>
              <el-table :data="addEditForm.rescueFeeStandardDetailsBenchmarkList" style="width: 100%">
                <el-table-column align="left" label="车型" prop="carCategory" width="120" />
                <el-table-column align="center" label="基价(元)" prop="benchmarkPrice" width="120">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.benchmarkPrice"
                      clearable
                      placeholder="请输入基价"
                      @input="handleNumberInput(scope.row, 'benchmarkPrice')"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="每增加一小时加收(不足1小时按1小时计算)" prop="overtimeFee"
                                 width="180">
                  <template slot="header">
                    <el-tooltip :content="'每增加一小时加收(不足1小时按1小时计算)'" effect="dark" placement="top">
                      <span class="label-text">每增加一小时加收(不足1小时按1小时计算)</span>
                    </el-tooltip>
                  </template>
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.overtimeFee"
                      clearable
                      placeholder="请输入加收金额"
                      @input="handleNumberInput(scope.row, 'overtimeFee')"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="overtravelFees"
                                 width="180">
                  <template slot="header">
                    <el-tooltip :content="'每增加1公里加收(不足1公里按1公里计算)'" effect="dark" placement="top">
                      <span class="label-text">每增加1公里加收(不足1公里按1公里计算)</span>
                    </el-tooltip>
                  </template>
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.overtravelFees"
                      clearable
                      placeholder="请输入加收金额"
                      @input="handleNumberInput(scope.row, 'overtravelFees')"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="备注" prop="remarks"
                                 width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remarks"
                      clearable
                      placeholder="请输入备注"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" min-width="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-link :disabled="btnLoading" :underline="false" type="danger"
                             @click="handleDeletebbb(scope.$index, scope.row)">
                      删除
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </fieldset>
          </div>
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">加收项（每次因特殊情况累计加收比例不超过50%）</div>
            </div>
          </div>
          <div>
            <fieldset>
              <el-table :cell-class-name="tableCellClassName" :data="addEditForm.rescueFeeStandardDetailsAdditionalList"
                        :summary-method="getSummaries"
                        show-summary style="width: 120%">
                <el-table-column align="left" label="加收项" prop="additionalName" width="120" />
                <el-table-column align="center" label="加收比例(%)" prop="overtravelProportion" width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.overtravelProportion"
                      :formatter="(value) => value + '%'"
                      clearable
                      placeholder="请输入加收比例"
                      @input="handleInput(scope.row, 'overtravelProportion')"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="备注" prop="remarks"
                                 width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remarks"
                      clearable
                      placeholder="请输入备注"
                    />
                  </template>
                </el-table-column>
                <!--              <el-table-column align="left" label="每增施1公里加收(不足1公里按1公里计算)" prop="phone" width="500" />-->
                <el-table-column align="center" label="操作" min-width="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-link :disabled="btnLoading" :underline="false" type="danger"
                             @click="handleDeleteotherbbb(scope.$index, scope.row)">
                      删除
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </fieldset>
          </div>
        </div>
        <!--        <el-row :gutter="24" style="margin-left: 80px">-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="附件">-->
        <!--              <el-upload-->
        <!--                :action="uploadUrl"-->
        <!--                :before-remove="beforeRemove"-->
        <!--                :file-list="fileList"-->
        <!--                :limit="3"-->
        <!--                :on-change="handleFileChange"-->
        <!--                :on-exceed="handleExceed"-->
        <!--                :on-preview="handlePreview"-->
        <!--                :on-remove="handleRemove"-->
        <!--                class="upload-demo"-->
        <!--                multiple>-->
        <!--                <el-button size="small" type="primary">点击上传</el-button>-->
        <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
        <!--              </el-upload>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import PubSub from 'pubsub-js'
import {tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/RescueFeeCq'


export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      uploadUrl: 'http://example.com/upload',
      fileList: [],
      upperLimit: 0, // 加收项合计值
      textarea: '',
      btnLoading: false,
      carColourList: [],
      addEditForm: {
        upperLimit: '',
        name: '',
        homeworkVehicles: '1',
        rescueFeeStandardDetailsBenchmarkList: [],
        rescueFeeStandardDetailsAdditionalList: [
          {
            additionalName: '夜间作业',
            overtravelProportion: ''
          },
          {
            additionalName: '危险货物车辆',
            overtravelProportion: ''
          },
          {
            additionalName: '隧道内作业',
            overtravelProportion: ''
          },
          {
            additionalName: '拖拽交通事故车辆',
            overtravelProportion: ''
          }
        ]
      },
      addEditRules: {
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        homeworkVehicles: [
          {required: true, message: '车类类型不能为空', trigger: 'blur'}
        ],
        upperLimit: [
          {required: true, message: '加收项上限不能为空', trigger: 'blur'}
        ],
        man: [
          {required: true, message: '公司法人不能为空', trigger: 'blur'}
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
    this.getCarColourList() // 在组件创建时获取字典数据
  },
  mounted() {
    // 原有的事件订阅
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      console.log(data, '99999')
      if (data.data.id) {
        this.id = data.data.id
        this.getDetail(data.data.id)
      } else {
      }
    })
  },
  methods: {
    // handleRemove(file, fileList) {
    //   console.log(file, fileList)
    // },
    // handlePreview(file) {
    //   console.log(file)
    // },
    // handleExceed(files, fileList) {
    //   this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    // },
    // beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除 ${file.name}？`)
    // },
    // handleFileChange(file, fileList) {
    //   this.fileList = fileList
    //   this.$refs.upload.submit()
    // },
    // submitUpload() {
    //   this.$refs.upload.submit()
    // },
    // 处理加收项上限输入事件
    handleUpperLimitInput() {
      let value = this.addEditForm.upperLimit
      value = value.replace(/[^\d.]/g, '')
      this.addEditForm.upperLimit = value
      if (value !== this.addEditForm.upperLimit) {
        this.$message.warning('只能输入数字！')
      }
    },
    // 打开页面执行
    openPage(data) {
      this.getCarColourList()
    },
    dictionaryEscape,
    // 获取车类字典数据
    async getCarColourList() {
      try {
        const response = getDictionaryByCode('zycl') // 调用获取字典数据的接口
        if (response) {
          this.carColourList = response.map(item => ({
            value: item.value,
            name: item.name
          }))
        } else {
          this.$message.error('获取车类字典数据失败')
        }
        // 获取车型字典数据（hc-stcx）
        const trailerResponse = getDictionaryByCode('hc-stcx')
        if (trailerResponse) {
          // 动态更新 rescueFeeStandardDetailsBenchmarkList 的 userId
          this.addEditForm.rescueFeeStandardDetailsBenchmarkList = trailerResponse.map(item => ({
            carCategory: item.name, // 使用字典中的 name 作为 userId
            benchmarkPrice: '', // 初始化基价
            overtravelFees: '', // 初始化增施一公里
            overtimeFee: '',//增加一小时
            remarks: ''
          }))
        } else {
          this.$message.error('获取车型字典数据失败')
        }
      } catch (error) {
        this.$message.error('获取车类字典数据时发生错误')
      }
    },
    //拖车删除一行
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addEditForm.rescueFeeStandardDetailsBenchmarkList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDeleteother(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addEditForm.rescueFeeStandardDetailsAdditionalList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 吊车删除一行
    handleDeletebbb(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addEditForm.rescueFeeStandardDetailsBenchmarkList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDeleteotherbbb(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addEditForm.rescueFeeStandardDetailsAdditionalList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 防抖函数
    debounce(func, wait) {
      let timeout
      return function(...args) {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
          func.apply(this, args)
        }, wait)
      }
    },
    // 处理数字输入-要求用户只能输入数字
    handleNumberInput(row, field) {
      // 获取输入的值
      let value = row[field]
      // 使用正则表达式过滤非数字字符
      value = value.replace(/[^\d.]/g, '') // 只允许数字和小数点
      // 更新绑定的值
      row[field] = value
      // 如果输入了非法字符，给出提示
      if (value !== row[field]) {
        this.$message.warning('只能输入数字！')
      }
    },
    // 处理输入事件
    handleInput(row, field) {
      // 获取输入的值
      let value = row[field]
      // 使用正则表达式过滤非数字字符
      value = value.replace(/[^\d.]/g, '') // 只允许数字和小数点
      // 更新绑定的值
      row[field] = value
    },
    // 合计方法
    getSummaries(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '加收项合计'
          return
        }
        if (column.property === 'overtravelProportion') {
          // 计算数值总和
          const total = data.reduce((sum, row) => {
            const value = Number(row.overtravelProportion) || 0
            return sum + value
          }, 0)
          sums[index] = `${total}%` // 显示时添加 %
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    // 动态设置单元格类名
    tableCellClassName({row, column, rowIndex}) {
      // 如果是合计行（最后一行）
      if (rowIndex === this.addEditForm.rescueFeeStandardDetailsAdditionalList.length) {
        return 'summary-row' // 返回自定义类名
      }
      return ''
    },
    // 关闭页面执行
    closePage() {
      // 清空表单数据
      this.addEditForm = {
        name: '',
        shortName: '',
        man: ''
      }
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {pubSub: this.pubSub})
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      this.addEditForm = await tableDetail(id)
    },

    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          // 计算加收项总和
          // this.upperLimit = this.addEditForm.rescueFeeStandardDetailsAdditionalList.reduce((sum, item) => {
          //   const value = Number(item.overtravelProportion) || 0
          //   return sum + value
          // }, 0)
          // 打印表单数据
          console.log('表单数据:', {...this.addEditForm})
          // 校验是否超过50%
          // if (this.upperLimit > 50) {
          //   this.$message.warning('加收项累计比例不得超过50%！')
          //   return
          // }
          // 保存数据（包含 upperLimit）
          const postData = {
            ...this.addEditForm
            // upperLimit: this.upperLimit
          }
          this.saveLoading = true
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            let {state, message} = await myInterFace(postData)
            if (state) {
              message = this.id ? '修改' : '新增'
              this.$message.success(`救援收费标准${message}成功`)
              // 清空表单数据
              this.addEditForm = {
                name: '',
                shortName: '',
                man: ''
              }
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      // 清空表单数据
      this.addEditForm = {
        name: '',
        shortName: '',
        man: ''

      }
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
fieldset {
  /* 表单页面居中，宽度50% ,legend颜色设置，legend圆角*/
  border: 1px solid #114066;
  border-radius: 8px;
  //margin: 0 auto;
  width: 0%;
}


.label-text {
  display: inline-block;
  max-width: 100%; /* 确保文本不超过列宽 */
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏溢出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>
