<template>
  <el-dialog
    :title="isEdit ? '编辑合同' : '新增合同'"
    :visible.sync="visible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="form.storeId"
          placeholder="请选择门店"
          style="width: 100%"
          clearable
          filterable
        >
          <el-option
            v-for="store in storeList"
            :key="store.id"
            :label="store.fullName"
            :value="store.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入标题"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select
          v-model="form.category"
          placeholder="请选择分类"
          style="width: 100%"
          clearable
        >
          <el-option label="门店" value="门店" />
          <el-option label="总部" value="总部" />
          <el-option label="宿舍" value="宿舍" />
        </el-select>
      </el-form-item>
      <el-form-item label="户名" prop="tenantName">
        <el-input
          v-model="form.tenantName"
          placeholder="请输入户名"
          maxlength="100"
        />
      </el-form-item>
      <el-form-item label="合同起始日期" prop="contractStartDate">
        <el-date-picker
          v-model="form.contractStartDate"
          type="datetime"
          placeholder="请选择合同起始日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="isEdit"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="合同结束日期" prop="contractEndDate">
        <el-date-picker
          v-model="form.contractEndDate"
          type="datetime"
          placeholder="请选择合同结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="isEdit"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="提前提醒天数" prop="reminderDays">
        <el-input-number
          v-model="form.reminderDays"
          :min="0"
          :max="365"
          placeholder="提前多少天提醒"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="押金" prop="deposit">
        <el-input-number
          v-model="form.deposit"
          :min="0"
          :precision="2"
          :disabled="isEdit"
          placeholder="请输入押金"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="月租" prop="monthlyRent">
        <el-input-number
          v-model="form.monthlyRent"
          :min="0"
          :precision="2"
          :disabled="isEdit"
          placeholder="请输入月租"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="缴租金额" prop="paymentAmount">
        <el-input-number
          v-model="form.paymentAmount"
          :min="0"
          :precision="2"
          :disabled="isEdit"
          placeholder="请输入每次交租的金额（通常=月租×交租周期）"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="交租周期" prop="paymentCycle">
        <el-input-number
          v-model="form.paymentCycle"
          :min="1"
          :max="12"
          :disabled="isEdit"
          placeholder="请输入交租周期（单位：月，如1、3、6等）"
          style="width: 100%"
        />
        <div style="color: #909399; font-size: 12px; margin-top: 4px;">
          提示：交租周期表示每隔几个月交一次租，范围1-12个月
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="附件" prop="attachment">
        <NCC-UploadImg
          v-model="attachmentList"
          :fileSize="30"
          sizeUnit="MB"
          :limit="9"
          type=""
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  createContract,
  updateContract,
  getContractInfo
} from '@/api/extend/contract'
import { getStoreSelector } from '@/api/extend/store'

export default {
  name: 'ContractFormDialog',
  data() {
    // 验证合同结束日期必须大于起始日期
    const validateEndDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择合同结束日期'))
        return
      }
      if (this.form.contractStartDate && value <= this.form.contractStartDate) {
        callback(new Error('合同结束日期必须大于起始日期'))
        return
      }
      callback()
    }

    return {
      visible: false,
      isEdit: false,
      submitLoading: false,
      form: {
        id: '',
        storeId: '',
        title: '',
        category: '',
        tenantName: '',
        contractStartDate: '',
        contractEndDate: '',
        reminderDays: 0,
        deposit: 0,
        monthlyRent: 0,
        paymentAmount: 0,
        paymentCycle: 1,
        remarks: '',
        attachment: ''
      },
      rules: {
        storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        contractStartDate: [
          { required: true, message: '请选择合同起始日期', trigger: 'change' }
        ],
        contractEndDate: [
          { required: true, validator: validateEndDate, trigger: 'change' }
        ],
        monthlyRent: [
          { required: true, message: '请输入月租', trigger: 'blur' },
          { type: 'number', min: 0, message: '月租必须大于等于0', trigger: 'blur' }
        ],
        paymentAmount: [
          { required: true, message: '请输入缴租金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '缴租金额必须大于等于0', trigger: 'blur' }
        ],
        paymentCycle: [
          { required: true, message: '请输入交租周期', trigger: 'blur' },
          { type: 'number', min: 1, max: 12, message: '交租周期必须在1-12个月之间', trigger: 'blur' }
        ]
      },
      storeList: [],
      editId: null,
      attachmentList: []
    }
  },
  methods: {
    // 打开新增弹窗
    openAdd() {
      this.isEdit = false
      this.editId = null
      this.resetForm()
      this.loadStoreList()
      this.visible = true
    },
    // 打开编辑弹窗
    async openEdit(id) {
      this.isEdit = true
      this.editId = id
      this.resetForm()
      this.loadStoreList()
      this.visible = true

      try {
        const response = await getContractInfo(id)
        if (response.code === 200 && response.data) {
          const data = response.data
          this.form = {
            id: data.id || '',
            storeId: data.storeId || '',
            title: data.title || '',
            category: data.category || '',
            tenantName: data.tenantName || '',
            contractStartDate: this.formatDateTime(data.contractStartDate) || '',
            contractEndDate: this.formatDateTime(data.contractEndDate) || '',
            reminderDays: data.reminderDays || 0,
            deposit: data.deposit || 0,
            monthlyRent: data.monthlyRent || 0,
            paymentAmount: data.paymentAmount || 0,
          paymentCycle: data.paymentCycle || 1,
          remarks: data.remarks || '',
          attachment: data.attachment || ''
        }
        // 如果有附件，转换为文件列表格式
        if (data.attachment) {
          try {
            // 尝试解析为 JSON 数组
            this.attachmentList = JSON.parse(data.attachment)
          } catch (e) {
            // 如果不是 JSON，可能是单个文件名，转换为数组格式
            if (data.attachment) {
              this.attachmentList = [
                {
                  name: data.attachment,
                  fileId: data.attachment,
                  url: ''
                }
              ]
            } else {
              this.attachmentList = []
            }
          }
        } else {
          this.attachmentList = []
        }
        } else {
          this.$message.error(response.msg || '获取详情失败')
          this.visible = false
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
        this.visible = false
      }
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: '',
        storeId: '',
        title: '',
        category: '',
        tenantName: '',
        contractStartDate: '',
        contractEndDate: '',
        reminderDays: 0,
        deposit: 0,
        monthlyRent: 0,
        paymentAmount: 0,
        paymentCycle: 1,
        remarks: '',
        attachment: ''
      }
      this.attachmentList = []
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    // 加载门店列表
    async loadStoreList() {
      try {
        const response = await getStoreSelector()
        if (response.code === 200 && response.data) {
          this.storeList = response.data.list || []
        }
      } catch (error) {
        console.error('加载门店列表失败:', error)
        this.storeList = []
      }
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        // 转换日期格式为 ISO 8601 格式
        const submitData = {
          storeId: this.form.storeId,
          title: this.form.title,
          category: this.form.category || '',
          tenantName: this.form.tenantName || '',
          contractStartDate: this.form.contractStartDate
            ? this.form.contractStartDate.replace(' ', 'T')
            : '',
          contractEndDate: this.form.contractEndDate
            ? this.form.contractEndDate.replace(' ', 'T')
            : '',
          reminderDays: this.form.reminderDays || 0,
          deposit: this.form.deposit || 0,
          monthlyRent: this.form.monthlyRent,
          paymentAmount: this.form.paymentAmount,
          paymentCycle: this.form.paymentCycle,
          remarks: this.form.remarks || '',
          attachment: this.attachmentList.length > 0 ? JSON.stringify(this.attachmentList) : ''
        }

        if (this.isEdit) {
          submitData.id = this.editId
        }

        this.submitLoading = true
        try {
          let response
          if (this.isEdit) {
            response = await updateContract(submitData)
          } else {
            response = await createContract(submitData)
          }

          if (response.code === 200) {
            this.$message.success(this.isEdit ? '更新成功' : '创建成功')
            this.handleClose()
            this.$emit('refresh')
          } else {
            this.$message.error(response.msg || '操作失败')
          }
        } catch (error) {
          console.error('提交失败:', error)
          this.$message.error(error.message || '操作失败')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false
      this.resetForm()
    },
    // 格式化日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      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}`
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>

