<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="50%"
    >
      <el-form ref="ruleForm" style="width: 600px;margin: 0 auto" :model="ruleForm" :rules="rules" label-width="160px" class="demo-ruleForm">
        <el-form-item label="注册号/统一社会信用代码" prop="uniscid">
          <el-input v-model="ruleForm.uniscid" placeholder="请输入注册号或统一社会信用代码" />
        </el-form-item>

        <el-form-item label="年报年度" prop="ancheyear">
          <el-select v-model="ruleForm.ancheyear" style="width:100%" placeholder="请选择年报年">
            <el-option
              v-for="item in ancheyearOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />>
          </el-select>
        </el-form-item>
        <el-form-item prop="timeStamp" label="填报时间">
          <el-date-picker
            v-model="ruleForm.timeStamp"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            value-format="yyyy-MM-dd hh:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="允许次数" prop="allowTime">
          <el-input-number
            v-model="ruleForm.allowTime"
            style="width:100%"
            :controls="false"
            :min="1"
            :max="1"
            disabled
          />
        </el-form-item>
        <el-form-item>
          <span v-if="title==='添加'">
            <el-button type="primary" :disabled="isSubmitting" @click="submitForm('ruleForm')">添加</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </span>
          <span v-else>
            <el-button type="primary" :disabled="isSubmitting" @click="submitForm('ruleForm')">修改</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { anModifyUpdata, anModifySave, anModifyGet, checkEBaseInfo } from '@/api/年报授权修改.js'
export default {
  data() {
    return {
      isSubmitting: false, // 新增状态变量
      dataId: '',
      title: '',
      dialogVisible: false,
      ruleForm: {
        allowTime: 0,
        endTime: '',
        beginTime: '',
        ancheyear: '',
        uniscid: '',
        timeStamp: []
      },
      ancheyearOptions: [],
      rules: {
        allowTime: [
          { required: true, message: '请输入允许次数', trigger: 'blur' }
        ],
        timeStamp: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        ancheyear: [
          { required: true, message: '请选择年报年', trigger: 'change' }
        ],
        uniscid: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    id(newVal, oldVal) {
      this.dataId = newVal
    }
  },
  created() {

  },
  mounted() {
    this.generateYearList()
  },
  methods: {
    submitForm(formName) {
      // 防止重复提交
      if (this.isSubmitting) {
        this.$message.warning('正在提交中，请勿重复点击！')
        return
      }

      const uniscid = this.ruleForm.uniscid
      checkEBaseInfo(uniscid).then(res => {
        if (res.code !== 0) {
          this.$message.warning(res.msg)
          return
        }
      })

      this.proceedWithSubmit(formName)
    },
    proceedWithSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isSubmitting = true // 开始提交，禁用按钮

          const api = this.title === '添加' ? anModifySave : anModifyUpdata
          const submitForm = {
            ...this.ruleForm,
            begintime: this.ruleForm.timeStamp[0],
            endtime: this.ruleForm.timeStamp[1]
          }

          api(submitForm)
            .then(res => {
              if (res.code === 0) {
                this.dialogVisible = false
                this.$message({
                  message: this.title + '成功！',
                  type: 'success'
                })
                this.$emit('refreshList')
              }
            })
            .catch(err => {
              console.error('提交失败:', err)
              this.$message.error('提交失败，请稍后重试！')
            })
            .finally(() => {
              this.isSubmitting = false // 提交完成，恢复按钮状态
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    generateYearList() {
      const currentDate = new Date()
      const currentYear = currentDate.getFullYear()
      const currentMonth = currentDate.getMonth() + 1 // 月份从 0 开始，需要加 1

      this.ancheyearOptions = []
      // 判断是否包含当前年份
      const includeCurrentYear = currentMonth >= 7
      // 计算起始年份
      const startYear = currentYear - 2
      // 生成年份选项
      for (let year = startYear; year <= currentYear; year++) {
        if ((year >= currentYear - 1) && !includeCurrentYear) {
          continue // 排除当前年份（如果不符合条件）
        }
        this.ancheyearOptions.push({ value: year, label: year + '年' })
      }
    },
    openDialog() {
      this.dialogVisible = true
      this.title = '添加'
      this.ruleForm = {
        allowTime: 0,
        endTime: '',
        beginTime: '',
        ancheyear: '',
        uniscid: '',
        timeStamp: []
      }
    },
    updateDialog(id) {
      this.dialogVisible = true
      this.title = '修改'
      anModifyGet(id).then(res => {
        const data = res.data
        const beginTime = data.begintime ? this.$moment(data.begintime).format('YYYY-MM-DD HH:mm:ss') : ''
        const endTime = data.endtime ? this.$moment(data.endtime).format('YYYY-MM-DD HH:mm:ss') : ''
        this.ruleForm = {
          id: data.id,
          allowTime: data.allowTime,
          ancheyear: data.ancheyear,
          uniscid: data.uniscid,
          timeStamp: [beginTime, endTime]
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
