<template>
  <div class="edit-add-detail">
    <div class="edit-add-detail-new-content">
      <div class="form-content">
        <el-form
          ref="addEditForm"
          :model="addEditForm"
          :rules="addEditRules"
          label-position="left"
          label-suffix="："
          label-width="150px"
        >
          <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="orgName">
                <el-input
                  v-model="addEditForm.orgName"
                  :disabled="true"
                  clearable
                  readonly
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="项目明细名称" prop="subjectName">
                <el-input
                  v-model="addEditForm.subjectName"
                  clearable
                  placeholder="请输入项目明细名称"
                ></el-input>
                <!--                 @input="handleInput"-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="项目明细编码" prop="subjectCode">
                <el-input
                  v-model="addEditForm.subjectCode"
                  clearable
                  placeholder="请输入项目明细编码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="项目明细类型" prop="typeId">
                <el-select
                  v-model="addEditForm.typeId"
                  placeholder="请选择项目明细类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('lsxmlx')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="规格型号" prop="model">
                <el-input
                  v-model="addEditForm.model"
                  clearable
                  placeholder="请输入规格型号"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="最低收费单价" prop="minPrice">
                <el-input
                  v-model.number="addEditForm.minPrice"
                  clearable
                  placeholder="请输入最低收费单价"
                  type="number"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="最高收费单价" prop="maxPrice">
                <el-input
                  v-model.number="addEditForm.maxPrice"
                  clearable
                  placeholder="请输入最高收费单价"
                  type="number"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap;margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="计费单位" prop="unit">
                <el-input
                  v-model="addEditForm.unit"
                  clearable
                  placeholder="请输入计费单位"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </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>

    <!--  外包公司选择弹层  -->
    <!--    <RoadSegmentDialog-->
    <!--      :is-show.sync="roadSegmentDialog"-->
    <!--      :selected-content.sync="addEditForm.roadSegment"-->
    <!--    />-->
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {
  tableAdd,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadDamageProjectDetails'
import {getDictionaryByCode} from '@/utils/dictionary'
import RoadSegmentDialog from './components/RoadSegmentDialog/index.vue'
import {orgTree} from '@/api/systemInterface'

export default {
  name: 'EditAddPage',
  components: {RoadSegmentDialog},
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      addEditForm: {
        orgId: '',
        orgName: '',
        orgFullId: '', // 新增 orgFullId 字段
        subjectCode: '',
        roadSegment: {}
      },
      addEditRules: {
        subjectName: [
          {required: true, message: '项目明细名称不能为空', trigger: ['blur']}
        ],
        subjectCode: [
          {required: true, message: '项目明细编码不能为空', trigger: ['blur']}
        ],
        typeId: [
          {
            required: true,
            message: '项目明细类型不能为空',
            trigger: ['change', 'blur']
          }
        ],
        model: [
          {
            required: false,
            message: '规格型号不能为空',
            trigger: ['change', 'blur']
          }
        ],
        minPrice: [
          {
            required: true,
            message: '最低收费单价不能为空',
            trigger: ['change', 'blur']
          },
          {
            validator: (rule, value, callback) => {
              if (value && value < 0) {
                callback(new Error('最低收费单价必须大于0'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur']
          }
        ],
        maxPrice: [
          {
            required: true,
            message: '最高收费单价不能为空',
            trigger: ['change', 'blur']
          },
          {
            validator: (rule, value, callback) => {
              if (value && value < this.addEditForm.minPrice) {
                callback(new Error('最高收费单价必须大于等于最低收费单价'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur']
          }
        ],
        unit: [
          {
            required: true,
            message: '计费单位不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'roadSegment.roadSegmentName': [
          {required: true, message: '所在路段不能为空', trigger: ['change']}
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null,
      cancelTokenSource: null, // 用于存储取消令牌
      roadSegmentDialog: false // 是否展示选择所在路段
    }
  },
  watch: {
    componentName(newVal) {
      if (newVal === this.$options.name) {
        this.openPage()
      } else {
        this.closePage()
      }
    }
  },
  created() {
    this.getOrgTreeData()
  },
  mounted() {
    // 订阅 TreeItemSelected 事件
    this.pubSub = PubSub.subscribe('TreeItemSelected', (_, nodeItem) => {
      this.addEditForm.orgName = nodeItem?.name || ''
      this.addEditForm.orgId = nodeItem?.id || ''
      this.addEditForm.orgFullId = nodeItem?.path || '' // 更新 orgFullId
    })
    // 原有的事件订阅
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        // 新增模式
        if (data.clearForm) {
          // 清空表单数据
          this.addEditForm = {
            orgId: '',
            orgName: '',
            orgFullId: '',
            name: '',
            shortName: '',
            man: '',
            code: '',
            tel: '',
            address: ''
          }
        }
        // 新增模式
        if (data.orgName) {
          // 如果传递了 orgName，则使用传递的值
          this.addEditForm.orgName = data.orgName
          this.addEditForm.orgId = data.catalogId
          this.addEditForm.orgFullId = data.path || '' // 更新 orgFullId
        } else if (this.treeData.length > 0) {
          // 否则使用 treeData 中的默认值
          this.addEditForm.orgName = this.treeData[0]?.name || ''
          this.addEditForm.orgId = this.treeData[0]?.id || ''
          this.addEditForm.orgFullId = this.treeData[0]?.path || '' // 更新 orgFullId
        }
      }
    })
  },
  methods: {
    getDictionaryByCode,
    // 获取公司树
    async getOrgTreeData() {
      let {value} = await orgTree() // 调用 API 获取树形数据
      this.treeData = value
      // 确保 treeData 数据加载完成后再设置初始值
      if (this.treeData.length > 0) {
        this.addEditForm.orgName = this.treeData[0]?.name || ''
        this.addEditForm.orgId = this.treeData[0]?.id || ''
      }
    },
    // 打开页面执行
    openPage() {},

    // 关闭页面执行
    closePage() {
      // 清空表单数据
      this.addEditForm = {
        orgId: '',
        orgName: '',
        orgFullId: '',
        name: '',
        shortName: '',
        man: '',
        code: '',
        tel: '',
        address: ''
      }
      const {pubSub, addEditRules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules
      })

      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      const {
        roadSegmentName = '',
        roadSegmentId = '',
        ...addEditForm
      } = await tableDetail(id)

      this.addEditForm = {
        ...addEditForm,
        roadSegment: {roadSegmentName, roadSegmentId}
      }
    },

    // 名称输入框事件
    // handleInput(chinese = '') {
    //   if (chinese) {
    //     getCodeRequest({chinese, type: '0'}).then(res => (this.addEditForm.subjectCode = res.value))
    //   } else {
    //     // 输入的值为空的时候，停止请求并清空编码
    //     getCodeRequest.cancel(_ => (this.addEditForm.subjectCode = ''))
    //   }
    // },

    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? tableEdit : tableAdd

          const {
            roadSegment: {roadSegmentName = '', roadSegmentId = ''} = {},
            ...addEditForm
          } = this.addEditForm

          try {
            let {state, message} = await myInterFace({
              ...addEditForm,
              roadSegmentName,
              roadSegmentId,
              orgFullId: this.addEditForm.orgFullId
            })
            // console.log(this.addEditForm, '新增的数据')
            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`路损项目明细${message}成功`)
              // 清空表单数据
              this.addEditForm = {
                orgId: '',
                orgName: '',
                orgFullId: '',
                name: '',
                shortName: '',
                man: '',
                code: '',
                tel: '',
                address: ''
              }
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      // 清空表单数据
      this.addEditForm = {
        orgId: '',
        orgName: '',
        orgFullId: '',
        name: '',
        shortName: '',
        man: '',
        code: '',
        tel: '',
        address: ''
      }
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';

.edit-add-detail {
  .edit-add-detail-new-content {
    width: 100%;
    display: flex;
    height: 0;
    flex: 1;
    column-gap: 20px;

    .form-content {
      flex: 1;
    }
  }
}
</style>
