<template>
  <div class="new-oa-workflow-form-edit-container">
    <el-card class="box-card">
      <div slot="header" class="flex justify-between">
        <span>{{ $t('newOaWorkflowFormEdit.title') }}</span>
      </div>
      <el-form>
        <el-row :gutter="20">
          <el-col :span="24">
            <div v-for="(item, index) in newOaWorkflowFormEditInfo.components" :key="index">
              <el-form-item v-if="item.type === 'textfield'" :label="item.label"
                :prop="'components.' + index + '.value'"
                :rules="[{ required: item.validate && item.validate.required, message: $t('newOaWorkflowFormEdit.requiredMessage') }]">
                <el-input v-model="item.value" :placeholder="item.description" clearable />
              </el-form-item>

              <el-form-item v-if="item.type === 'number'" :label="item.label" :prop="'components.' + index + '.value'">
                <el-input-number v-model="item.value" :placeholder="item.description" controls-position="right" />
              </el-form-item>

              <el-form-item v-if="item.type === 'textarea'" :label="item.label"
                :prop="'components.' + index + '.value'">
                <el-input v-model="item.value" type="textarea" :placeholder="item.description" :rows="4" />
              </el-form-item>

              <el-form-item v-if="item.type === 'textdate'" :label="item.label"
                :prop="'components.' + index + '.value'">
                <el-date-picker v-model="item.value" type="date" :placeholder="item.description"
                  value-format="yyyy-MM-dd" />
              </el-form-item>

              <el-form-item v-if="item.type === 'textdatetime'" :label="item.label"
                :prop="'components.' + index + '.value'">
                <el-date-picker v-model="item.value" type="datetime" :placeholder="item.description"
                  value-format="yyyy-MM-dd HH:mm:ss" />
              </el-form-item>

              <el-form-item v-if="item.type === 'checkbox'" :label="item.label"
                :prop="'components.' + index + '.value'">
                <el-checkbox-group v-model="item.value">
                  <el-checkbox :label="item.value">{{ item.label }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>

            <upload-file ref="uploadFile" :call-back-listener="'newOaWorkflowFormEdit'"
              :call-back-function="'fileName'" />

            <div class="form-footer">
              <el-button type="primary" @click="_submitFormData">
                <i class="el-icon-check"></i>
                {{ $t('newOaWorkflowFormEdit.submit') }}
              </el-button>
              <el-button type="warning" @click="closeEditInfo">
                {{ $t('newOaWorkflowFormEdit.cancel') }}
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { queryOaWorkflowForm, queryOaWorkflowFormData, updateOaWorkflowFormData } from '@/api/oa/newOaWorkflowFormEditApi'
import UploadFile from '@/components/oa/uploadFile'

export default {
  name: 'NewOaWorkflowFormEditList',
  components: {
    UploadFile
  },
  data() {
    return {
      newOaWorkflowFormEditInfo: {
        formJson: {},
        components: [],
        conditions: {},
        flowId: '',
        id: '',
        fileName: '',
        realFileName: ''
      }
    }
  },
  created() {
    this.newOaWorkflowFormEditInfo.flowId = this.$route.query.flowId
    this.newOaWorkflowFormEditInfo.id = this.$route.query.id
    this._listOaWorkflowFormEdit(1, 100)
  },
  methods: {
    async _listOaWorkflowFormEdit(page, rows) {
      try {
        const params = {
          page,
          row: rows,
          flowId: this.newOaWorkflowFormEditInfo.flowId
        }

        const { data } = await queryOaWorkflowForm(params)
        const formData = JSON.parse(data[0].formJson)
        this.newOaWorkflowFormEditInfo.formJson = formData
        this.newOaWorkflowFormEditInfo.components = formData.components
        this._listOaWorkflowDetails()
      } catch (error) {
        console.error('获取表单数据失败:', error)
      }
    },
    async _listOaWorkflowDetails() {
      try {
        const params = {
          page: 1,
          row: 1,
          id: this.newOaWorkflowFormEditInfo.id,
          flowId: this.newOaWorkflowFormEditInfo.flowId
        }

        const { data } = await queryOaWorkflowFormData(params)
        const detailData = data[0]

        this.newOaWorkflowFormEditInfo.components.forEach(item => {
          item.value = detailData[item.key]
        })

        if (detailData.files) {
          this.newOaWorkflowFormEditInfo.fileName = detailData.files[0].fileName
          this.newOaWorkflowFormEditInfo.realFileName = detailData.files[0].realFileName
          this.$refs.uploadFile.notifyVedio(detailData.files[0].fileName)
        }
      } catch (error) {
        console.error('获取表单详情失败:', error)
      }
    },
    async _submitFormData() {
      try {
        const components = this.newOaWorkflowFormEditInfo.components
        const formData = {
          id: this.newOaWorkflowFormEditInfo.id,
          flowId: this.newOaWorkflowFormEditInfo.flowId,
          fileName: this.newOaWorkflowFormEditInfo.fileName,
          realFileName: this.newOaWorkflowFormEditInfo.realFileName
        }

        components.forEach(item => {
          if (item.validate && item.validate.required && !item.value) {
            this.$message.error(item.label + this.$t('newOaWorkflowFormEdit.requiredMessage'))
            throw new Error(item.label + this.$t('newOaWorkflowFormEdit.requiredMessage'))
          }

          if (item.type !== 'button' && item.type !== 'text') {
            formData[item.key] = item.value
            if (item.type === 'checkbox') {
              formData[item.key] = item.value.length > 0 ? item.value[0] : ''
            }
          }
        })

        const res = await updateOaWorkflowFormData(formData)
        if (res.code === 0) {
          this.$message.success(this.$t('newOaWorkflowFormEdit.submitSuccess'))
          this.closeEditInfo()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        this.$message.error(this.$t('newOaWorkflowFormEdit.submitError'))
      }
    },
    closeEditInfo() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.new-oa-workflow-form-edit-container {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;
  }

  .form-footer {
    margin-top: 20px;
    text-align: right;
  }

  .el-form-item {
    margin-bottom: 22px;
  }
}
</style>